c# - 创建一个 PowerShell 管道以在 C# 中读取异步

标签 c# powershell

我想在 C# 中创建与此等效的内容:

PS > Get-Disk | Get-Partition

我试过这个:

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()
}

但是这不是同步。我想创建管道并异步读取它。是否可以?

谢谢!

注意:这是相关的,但不是异步的:How pipe powershell commands in c#

最佳答案

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

这是使用 System.Management.Automation 中的 PowerShell 对象

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);
}

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

关于c# - 创建一个 PowerShell 管道以在 C# 中读取异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139976/

相关文章:

c# - XmlDocument 并使用 xPath 获取特定属性

c# - 错误 (502) 网关错误 : When trying to access chatbot deployed on Azure using WebChat channel

powershell - windows powershell 在 for each 循环期间显示管道中的当前变量

regex - PowerShell 正则表达式来挑选耗时

arrays - PowerShell 电子邮件阵列

c# - 尝试调用 Reporting Services Web 方法时出现 NotImplementedException

c# - 一次在同一张表中执行多个插入操作

powershell - Azure Runbook 错误,AzureRmStorageAccountKey 无法索引到空数组

powershell - 在powershell中添加属性

c# - 无效的 Intellisense 错误 CS0103 ASP.NET 网站 “The name does not exist in the current context”