将PowerShell命令插入c#

时间:2014-01-15 12:45:07

标签: c# powershell

我想在C#项目中使用此PowerShell命令:

Get-VM -Name Win8-Henry | Get-VMNetworkAdapter | Select MacAddress

这就是我通常在c#中做的事情:

public static void MacAdd(string machineName,Runspace run) {
    // Get-VM -Name Win8-Henry | Get-VMNetworkAdapter | Select MacAddress
    Command command = new Command("Get-VM");
    command.Parameters.Add("Name", machineName);

    using (Pipeline hostPipeline = run.CreatePipeline())
    {
        hostPipeline.Commands.Add(command);
        Collection<PSObject> echos = hostPipeline.Invoke();
        hostPipeline.Stop();
    }
}

我需要帮助的是添加第二个命令,然后使用管道。

3 个答案:

答案 0 :(得分:2)

使用AddScript() method上的PowerShell class

var Command = String.Format("Get-VM -Name {0} | Get-VMNetworkAdapter | Select MacAddress", computername);
var PowerShell = PowerShell.Create();
PowerShell.AddScript(Command);
PowerShell.Invoke();

答案 1 :(得分:0)

只需将其他命令添加到管道中:)

hostPipeline.Commands.Add(new Command("Get-VMNetworkAdapter"));

答案 2 :(得分:0)

当我有一个我需要在应用程序中执行的脚本时,分享我的工作。然后我可以轻松地替换参数(即“$!$ machineName $!$”)并干净利落地获得结果。

Dim lxScript As XElement = <Script>
.{
Get-VM -Name $!$machineName$!$ | Get-VMNetworkAdapter | Select MacAddress
}                         
                     </Script>
相关问题