C#中执行PowerShell 脚本

来源:互联网 发布:一键安装php集成环境 编辑:程序博客网 时间:2024/05/17 14:18

在C#中调用powershell脚本,需要引用的namespace如下:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

添加System.Management.Automation.dll的引用,需要使用浏览,如果不知道位置,可以先在本机查找下。

代码如下:

 

//RunPowershell(@".\x.ps1", "");
         private Collection<PSObject> RunPowershell(string filePath, string parameters)
         {
             RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
             Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
             runspace.Open();
             RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
             Pipeline pipeline = runspace.CreatePipeline();
             Command scriptCommand = new Command(filePath);
             Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
 
             string[] tempParas = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
             for (int i = 0; i < tempParas.Length; i += 2)
             {
                 CommandParameter commandParm = new CommandParameter(tempParas[i], tempParas[i + 1]);
                 commandParameters.Add(commandParm);
                 scriptCommand.Parameters.Add(commandParm);
             }
 
             pipeline.Commands.Add(scriptCommand);
             Collection<PSObject> psObjects;
             psObjects = pipeline.Invoke();
 
             if (pipeline.Error.Count > 0)
             {
                 throw new Exception("脚本执行失败");
             }
 
             runspace.Close();
 
             return psObjects;
         }

 

 

powershell脚本执行的结果存在Collection<PSObject>集合中。

原创粉丝点击