创建PowerShell管道以在C#中读取异步

Sup*_*JMN 5 c# powershell

我想在C#中创建等效的:

PS > Get-Disk | Get-Partition
Run Code Online (Sandbox Code Playgroud)

我试过这个:

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()
}
Run Code Online (Sandbox Code Playgroud)

但这不是同步.我想创建管道并异步读取它.可能吗?

谢谢!

注意:这是相关的,但不是async:如何在c#中使用pipe powershell命令

ivc*_*ubr 2

我在让它识别命令时遇到了一些问题,Get-Disk|Get-Partition所以我选择了dir|select Name. 希望在您的环境中您可以替换Get-Disk|Get-Partition回来。

这是使用PowerShell来自的对象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);
}
Run Code Online (Sandbox Code Playgroud)

为了举例,我只是调用.BeginInvoke()并使用.EndInvoke(async)来演示其中的异步部分。您需要根据您的需要进行调整(即以不同的方式处理结果等),但我过去PowerShell多次使用过这个类,发现它非常有帮助。