Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a PowerShell pipeline to read async in C#

Tags:

c#

powershell

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#

like image 325
SuperJMN Avatar asked Oct 28 '22 09:10

SuperJMN


1 Answers

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.

like image 144
ivcubr Avatar answered Nov 15 '22 05:11

ivcubr