调用PowerShell与C# [英] Calling PowerShell From C#

查看:267
本文介绍了调用PowerShell与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时调用

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

然而,这是行不通的。在解决方法我想出了用的foreach对象,然后传递数组作为 InputObject {$ _} 过程

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

虽然上述工作code是有使用调用传球输入数组中,因为我会虽然,这将是调用的可取方式中的任何方式呢?

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> result = ps.Invoke();
    foreach (PSObject result in results)
                {
                    Console.WriteLine(result);
                }

返回exactely:

returns exactely:

2
4
6

这篇关于调用PowerShell与C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆