Jade M
Jade M

Reputation: 3101

C# Piping commands into PowerShell

I need to run two powershell commands one after the other, should I create a pipeline twice or is there a better option? Thanks

Runspace myRunSpace = RunspaceFactory.CreateRunspace(rc);
            myRunSpace.Open();

            Pipeline pipeLine = myRunSpace.CreatePipeline();

            using (pipeLine)
            {
                Command myCommand = new Command("Get-Command...");
            }

            Pipeline pipeLine2 = myRunSpace.CreatePipeline();

            using (pipeLine2)
            {
                Command myCommand = new Command("Get-Command...");
            }

Upvotes: 1

Views: 1072

Answers (2)

Kenan E. K.
Kenan E. K.

Reputation: 14111

A pipeline is, according to msdn, like an "assembly line", so if the results of the first command have nothing to do with the second command, you do not need a Pipeline, you can use a ScriptBlock instead, and invoke it with a RunspaceInvoke object.

See an example here.

Upvotes: 1

Jay Bazuzi
Jay Bazuzi

Reputation: 46506

Would you be happier with your code if you wrote:

using (Pipeline pipeLine = myRunSpace.CreatePipeline())
{
    Command myCommand = new Command("Get-Command...");
}

?

Upvotes: 0

Related Questions