簡體   English   中英

使用來自 C# 的 PowerShell 主機,我如何才能獲得 output?

[英]Using the PowerShell host from C# how can I get the output?

具有以下 NET 5 控制台應用程序:

static void Main(string[] args)
{
    using var ps = PowerShell.Create();
    // ps.AddCommand("Get-Service");
    ps.AddStatement().AddCommand("Get-Service");
    ps.Invoke();
}

調用似乎沒有錯誤地執行,但是 output 去哪里了? 我已經嘗試了AddCommandAddStatement ,還檢查了調試器中的ps變量,沒有 output 的跡象。 我確實發現了ps.Streams.Information但它是空的。

PowerShell.Invoke方法的文檔中所述,它返回一個集合,其中包含 PowerShell 操作產生的任何結果。

因此,你可以寫

static void Main(string[] args)
{
    using var ps = PowerShell.Create();
    ps.AddStatement().AddCommand("Get-Service");
    var results = ps.Invoke();

    foreach (var result in results)
    {
        Console.WriteLine(result);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM