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;
}