在C#中运行PowerShell

C#中运行PowerShell需要用到System.Management.Automation.dll。在Visual Studio中可以通过NuGet添加引用,package名字为“System.Management.Automation”。

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
 {
     pipeline.Commands.AddScript("Powershell Script"");
     // Get result
    Collection<PSObject> results = pipeline.Invoke();     
 }
runspace.Close();

在64位系统上调试时,可能需要将Build平台改为x64,否则系统调用的Powershell为32位的。

原文地址:https://www.cnblogs.com/urwlcm/p/4614322.html