我正在使用System.Management.Automation
DLL,它允许我在 C# 应用程序中调用 PowerShell,如下所示:
PowerShell.Create().AddScript("Get-Process").Invoke();
我想要做的是调用 PowerShell 但提供输入列表。例如,在:
1, 2, 3 | ForEach-Object { $_ * 2 }
1, 2, 3
我试图在调用时提供左侧:
// powershell is a PowerShell Object
powershell.Invoke(new [] { 1, 2, 3 });
但是,这不起作用。我想出的解决方法ForEach-Object
是使用数组,然后将数组作为 anInputObject
和{ $_ }
as传递Process
:
// create powershell object
var powershell = PowerShell.Create();
// input array 1, 2, 3
Command inputCmd = new Command("ForEach-Object");
inputCmd.Parameters.Add("InputObject", new [] { 1, 2, 3 });
inputCmd.Parameters.Add("Process", ScriptBlock.Create("$_"));
powershell.Commands.AddCommand(inputCmd);
// ForEach-Object { $_ * 2 }
Command outputCmd = new Command("ForEach-Object");
outputCmd.Parameters.Add("Process", ScriptBlock.Create("$_ * 2"));
powershell.Commands.AddCommand(outputCmd);
// invoke
var result = powershell.Invoke();
虽然上面是工作代码,但有什么方法可以使用Invoke
传入输入数组,因为我会认为这是调用它的理想方式?