从C#调用PowerShell

Tah*_*san 6 c# powershell automation

我正在使用System.Management.AutomationDLL,它允许我在我的C#应用​​程序中调用PowerShell,如下所示:

PowerShell.Create().AddScript("Get-Process").Invoke();
Run Code Online (Sandbox Code Playgroud)

我要做的是调用PowerShell但提供输入列表.例如,在:

1, 2, 3 | ForEach-Object { $_ * 2 }
Run Code Online (Sandbox Code Playgroud)

1, 2, 3在调用时试图提供左侧:

// powershell is a PowerShell Object
powershell.Invoke(new [] { 1, 2, 3 });
Run Code Online (Sandbox Code Playgroud)

但这不起作用.该解决方法我想出了使用了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();
Run Code Online (Sandbox Code Playgroud)

虽然以上是工作代码是否有任何方法使用Invoke传入输入数组,因为我会尽管这是调用它的理想方式?

CB.*_*CB. 10

有点迟了但是:

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);
}
Run Code Online (Sandbox Code Playgroud)

收益:

2
4
6
Run Code Online (Sandbox Code Playgroud)