1

I want to use this PowerShell command in a C# project:

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

This is what I normally do in 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();
    }
}

What I need help with is adding the second command, and then using the pipeline.

1
  • hostPipeline.Commands.Add(anotherCommand) and then Invoke() ? Commented Jan 15, 2014 at 12:55

3 Answers 3

2

Use the AddScript() method on the PowerShell class.

var Command = String.Format("Get-VM -Name {0} | Get-VMNetworkAdapter | Select MacAddress", computername);
var PowerShell = PowerShell.Create();
PowerShell.AddScript(Command);
PowerShell.Invoke();
Sign up to request clarification or add additional context in comments.

Comments

0

Just add the other commands to the pipeline too :)

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

Comments

0

Just to share what I do when I have a script that I need to execute in an application. I can then replace the parameters (i.e., "$!$machineName$!$" easily and get the result cleanly.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.