C#中執行PowerShell 腳本

在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>集合中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章