从C#调用PowerShell
我正在使用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
,然后将数组作为InputObject
传递,并使用{ $_ }
作为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
传入输入数组,因为我会有这种方式调用它?
有点晚了但是:
PowerShell ps = PowerShell.Create(); ps.Runspace.SessionStateProxy.SetVariable("a", new int[] { 1, 2, 3 }); ps.AddScript("$a"); ps.AddCommand("foreach-object"); ps.AddParameter("process", ScriptBlock.Create("$_ * 2")); Collection results = ps.Invoke(); foreach (PSObject result in results) { Console.WriteLine(result); }
收益:
2 4 6
我完成了我的研究和PowerShell.Invoke( IEnumerable )
将设置列表中第一个命令的InputObject
。 因此,我们可以将其传递给Invoke
方法,而不是在上面的inputCmd
上设置InputObject
。 我们仍然需要第一个ForEach-Object
调用来传递输入数组。