C# 从C调用PowerShell#

C# 从C调用PowerShell#,c#,powershell,automation,C#,Powershell,Automation,我正在使用System.Management.AutomationDLL,它允许我在C#应用程序中调用PowerShell,如下所示: PowerShell.Create().AddScript("Get-Process").Invoke(); 我试图做的是调用PowerShell,但提供输入列表。例如,在: 1, 2, 3 | ForEach-Object { $_ * 2 } 调用时,我试图提供左侧1、2、3: // powershell is a PowerShell Object p

我正在使用
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对象
,然后将数组作为
InputObject
传递,将
{$}
作为
过程

// 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.Invoke(IEnumerable)
将设置列表中第一个命令的
InputObject
。因此,我们可以通过
Invoke
方法传递它,而不是在上面的
inputCmd
上设置
InputObject
。我们仍然需要第一个
ForEach对象
调用来将输入数组传递给。

有点晚,但是:

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);
}

这是可行的,但您将
1,2,3
作为字符串而不是数组传递,即
newint[]{1,2,3}
。如果我要将结构化数据传递到管道,则需要第二个。@Tahirhasan我知道传递创建的.net对象的唯一方法是使用
SessionStateProxy.SetVariable(字符串名称,对象值)
。请看我编辑的答案。您已经回答了我关于如何使用数组启动管道的问题(而不使用问题中所述的
InputObject
参数将其传递给
ForEach Object
)。谢谢。@TahirHassan很乐意帮忙!这真是天才!我永远不会在那里找它!
2
4
6