从 C# 调用 PowerShell [英] Calling PowerShell From C#
问题描述
我正在使用 System.Management.Automation
DLL,它允许我在我的 C# 应用程序中调用 PowerShell,如下所示:
I am using System.Management.Automation
DLL which allows me to call PowerShell within my C# application like so:
PowerShell.Create().AddScript("Get-Process").Invoke();
我想做的是调用 PowerShell 但提供输入列表.例如,在:
What I am trying to do is call PowerShell but supply the input list. For example, in:
1, 2, 3 | ForEach-Object { $_ * 2 }
我试图在调用时提供左侧 1, 2, 3
:
I am trying to supply the left hand side 1, 2, 3
when invoking:
// powershell is a PowerShell Object
powershell.Invoke(new [] { 1, 2, 3 });
然而这行不通.我想出的 解决方法是使用 ForEach-Object
然后将数组作为 InputObject
传递给 { $_ }
作为 Process
:
However this does not work. The workaround I came up with was using ForEach-Object
and then passing the array as an InputObject
with the { $_ }
as the 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
传入输入数组,因为我认为这是调用它的理想方式?
Although the above is working code is there any way of using Invoke
passing in the input array because I would have though that this would be desirable way of calling it?
推荐答案
有点晚但是:
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<PSObject> results = ps.Invoke();
foreach (PSObject result in results)
{
Console.WriteLine(result);
}
返回:
2
4
6
这篇关于从 C# 调用 PowerShell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!