[英]Creating a PowerShell pipeline to read async in C#
我想在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()
}
但這不是同步 。 我想創建管道並異步讀取它。 可能嗎?
謝謝!
注意:這是相關的,但不是async: 如何在c#中使用pipe powershell命令
我有一些問題讓它識別Get-Disk|Get-Partition
命令,所以我dir|select Name
了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
類,並發現它非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.