Scorp
Scorp

Reputation: 247

Invoke powershell cmdlets in pipeline in C#

Does Pipeline.Invoke in System.Management.Automation.Runspaces call the cmdlets present in the Commands collection in pipeline or executes individually in C#?

I have added two cmdlets to the pipeline and called Pipeline.Invoke, however the output of first cmdlets is not recognized as pipeline input and am getting error related to the missing mandatory field for second cmdlet.

Can we achieve the pipeline calling in C# like we do it in PowerShell console A | B ?

Upvotes: 1

Views: 354

Answers (1)

Raffaello
Raffaello

Reputation: 1706

Pipeline can execute multiple commands like if using the pipe operator |.

It is enough to add multiple commands to the pipeline in the Commands property e.g. pipeline.Commands.Add(myCmd).Add(myPipedCmd);

For e.g. to run Get-Item | Select Name

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command dir = new Command("Get-Item");
pipeline.Commands.Add(dir);
Command select = new Command("Select");
select.Parameters.Add(null, "Name");
pipeline.Commands.Add(select);
var out1 = pipeline.Invoke();
// ...
runspace.Close();

Upvotes: 1

Related Questions