0

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.

g.pickardou
  • 32,346
  • 36
  • 123
  • 268
  • 2
    `var results = ps.Invoke();`. See [the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell.invoke?view=powershellsdk-7.0.0#System_Management_Automation_PowerShell_Invoke) – Aluan Haddad Feb 28 '21 at 08:18
  • 1
    many thx, it's an answer – g.pickardou Feb 28 '21 at 08:21

1 Answers1

1

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);
    }
}
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84