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

327 Views Asked by At

Having the following NET 5 Console application:

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? I've tried both AddCommand and AddStatement, and also examined the ps variable in debugger, no signs of output. I did discover the ps.Streams.Information but it is empty.

1

There are 1 best solutions below

0
On BEST ANSWER

As detailed in the documentation for the PowerShell.Invoke method, it returns a collection containing any results that the PowerShell operation produced.

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