如何使用参数调用c#中的powershell脚本

Sun*_*rxz 2 c# powershell

我试图用c#中的参数调用powershell脚本.是否有任何选项只提供powershell脚本文件和参数,而不是将整个powershell命令作为c#代码中的字符串.

kal*_*zel 7

快速谷歌搜索真的为您提供所需的一切.这个来自http://www.devx.com/tips/Tip/42716

你需要参考System.Management.Automation 然后使用

using System.Management.Automation;
using System.Management.Automation.Runspaces;
Run Code Online (Sandbox Code Playgroud)

创建一个运行空间来托管PowerScript环境:

Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
Run Code Online (Sandbox Code Playgroud)

使用运行空间,为cmdlet创建一个新管道:

Pipeline pipeline = runSpace.CreatePipeline();
Run Code Online (Sandbox Code Playgroud)

创建Command对象以表示要执行的cmdlet,并将它们添加到管道中.此示例检索所有进程,然后按内存使用情况对其进行排序.

Command getProcess = new Command("Get-Process");
Command sort = new Command("Sort-Object");
sort.Parameters.Add("Property", "VM"); 
pipeline.Commands.Add(getProcess);
pipeline.Commands.Add(sort);
Run Code Online (Sandbox Code Playgroud)

上述代码的功能与以下PowerShell命令行相同:

PS > Get-Process | Sort-Object -Property VM

最后,执行管道中的命令并对输出执行以下操作:

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
  Process process = (Process)psObject.BaseObject;
  Console.WriteLine("Process name: " + process.ProcessName);
}
Run Code Online (Sandbox Code Playgroud)