2014-01-15 56 views
1

我想在C#項目中使用此PowerShell命令:插入PowerShell命令到C#

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

我需要什麼是幫助添加第二個命令,然後使用管道。

+0

hostPipeline.Commands.Add (anotherCommand)然後調用()? – NValchev

回答

2

使用AddScript() methodPowerShell class

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

就在前命令添加到管線太:)

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

只是爲了分享時,我有一個腳本,我需要在應用程序中執行我做什麼。然後,我可以代替參數(即 「$!$ MACHINENAME $ $!」 容易和乾淨得到的結果。

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