我正在尝试使用来自 c# 的参数调用 powershell 脚本。是否有任何选项可以只提供 powershell 脚本文件和参数,而不是将整个 powershell 命令作为 c# 代码中的字符串提供。
最佳答案
一个快速的谷歌搜索确实可以为您提供所需的一切。这个来自http://www.devx.com/tips/Tip/42716
您需要引用 System.Management.Automation
然后使用
using System.Management.Automation;
using System.Management.Automation.Runspaces;
创建一个运行空间来托管 PowerScript 环境:
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
使用运行空间,为您的 cmdlet 创建一个新的管道:
Pipeline pipeline = runSpace.CreatePipeline();
创建命令对象来表示您要执行的 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);
上述代码的功能与以下 PowerShell 命令行相同:
PS > 获取进程 |排序对象-属性 VM
最后,执行管道中的命令并对输出做一些处理:
Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
Process process = (Process)psObject.BaseObject;
Console.WriteLine("Process name: " + process.ProcessName);
}
关于c# - 如何使用参数在 c# 中调用 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752630/