Im Kommentarabschnitt gab @Prageeth Saravanan einen nützlichen Link zur Integration von PowerShell in C#.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
Schnell Beispiel:
Zuerst hatte ich diesen Refs enthalten:
System.Management.Automation
System.Collections.ObjectModel
Hinweis: Sie benötigen ein NuGet Paket für "Management.Automation" hinzufügen . Geben Sie "System.Management.Automation" ein und Sie werden es finden.
C# -Code:
//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();
}
}
hoffe, das hilft!
Sie müssen ein PS-Skript erstellen und es aus C# aufrufen. Siehe https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ –
Haben Sie ein Update zu diesem Thema? –
Ich habe gerade den answert @ TomSun-MSFT gepostet –