В разделе комментариев @Prageeth Saravanan дал полезную ссылку о том, как интегрировать PowerShell в C#.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
Быстрый пример:
Сначала я должен был включать в себя эти рефов:
System.Management.Automation
System.Collections.ObjectModel
Примечание: Вам нужно добавить пакет NuGet для "Management.Automation" , Просто введите «System.Management.Automation», вы найдете его.
C# код:
//The first step is to create a new instance of the PowerShell class
using (PowerShell powerInstance = PowerShell.Create()) //PowerShell.Create() creates an empty PowerShell pipeline for us to use for execution.
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; $d; $s; $param1; get-service");
// use "AddParameter" to add a single parameter to the last command/script on the pipeline.
PowerShellInstance.AddParameter("param1", "parameter 1 value!");
//Result of the script with Invoke()
Collection<PSObject> result = powerInstance.Invoke();
//output example : @{yourProperty=value; yourProperty1=value1; yourProperty2=StoppedDeallocated; PowerState=Stopped; OperationStatus=OK}}
foreach (PSObject r in result)
{
//access to values
string r1 = r.Properties["yourProperty"].Value.ToString();
}
}
Надеется, что это помогает!
Вам нужно будет создать сценарий PS и вызвать его из C#. См. Https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ –
У вас есть обновление об этой теме? –
Я только что разместил answert @ TomSun-MSFT –