5

I would like to create the equivalent in C# of this:

PS > Get-Disk | Get-Partition

I've tried with this:

using (var r = RunspaceFactory.CreateRunspace())
{             
    var pipeline = r.CreatePipeline();

    var gd = new Command("Get-Disk");
    var gv = new Command("Get-Partition");

    pipeline.Commands.Add(gp);
    pipeline.Commands.Add(gv);

    var results = pipeline.Invoke()
}

But this is not sync. I would like to create the pipeline and read from it asynchronously. Is it possible?

Thank you!

NOTE: This is related, but not async: How pipe powershell commands in c#

SuperJMN
  • 13,110
  • 16
  • 86
  • 185

1 Answers1

2

I was having some issues getting it to recognize the Get-Disk|Get-Partition command so I settled for dir|select Name. Hopefully in your environment you can substitute Get-Disk|Get-Partition back in.

This is using the PowerShell object from System.Management.Automation

using (PowerShell powershell = PowerShell.Create()) {
    powershell.AddScript("dir | select Name");

    IAsyncResult async = powershell.BeginInvoke();

    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject result in powershell.EndInvoke(async)) {
        stringBuilder.AppendLine(result.ToString());
    }

    Console.WriteLine(stringBuilder);
}

For sake of example I am just calling .BeginInvoke() and the using .EndInvoke(async) to demonstrate the asynchronous part of this. You will need to adapt this to your needs (i.e. process the results differently, etc.) but I have used this PowerShell class many times in the past and found it very helpful.

ivcubr
  • 1,988
  • 9
  • 20
  • 28