简体   繁体   English

使用来自 C# 的 PowerShell 主机,我如何才能获得 output?

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

Having the following NET 5 Console application:具有以下 NET 5 控制台应用程序:

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

The calls seems to be executed with no error, but where the output goes?调用似乎没有错误地执行,但是 output 去哪里了? I've tried both AddCommand and AddStatement , and also examined the ps variable in debugger, no signs of output.我已经尝试了AddCommandAddStatement ,还检查了调试器中的ps变量,没有 output 的迹象。 I did discover the ps.Streams.Information but it is empty.我确实发现了ps.Streams.Information但它是空的。

As detailed in the documentation for the PowerShell.Invoke method, it returns a collection containing any results that the PowerShell operation produced.PowerShell.Invoke方法的文档中所述,它返回一个集合,其中包含 PowerShell 操作产生的任何结果。

Thus, you can write因此,你可以写

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