C# PowerShell does not capture PowerShell.Streams when using AddCommand but does when using AddScript

129 views Asked by At

I am encountering a very strange behavior when using PowerShell in C#. When I execute

InitialSessionState s = InitialSessionState.CreateDefault2();
var ps = PowerShell.Create(s);


ps.AddCommand("Write-Information")
    .AddArgument("<test>")
    .Invoke();

// Writes 0. But why?
Console.WriteLine(PS.Streams.Information.Count);

no streams (Stream.Information, Stream.Error, ...) are captured. But when I use

ps.AddScript("Write-Information '<test>'")
    .Invoke();

// Writes 1 as expected
Console.WriteLine(PS.Streams.Information.Count);

Everything works as expected. Can anybody explain this difference? Am I missing some conceptions? How can there be a difference? How can I capture the streams of a AddCommand invocation?

Thanks for any input on this!

1

There are 1 answers

0
Börg On

Sorry for the confusion, it was my bad. I was calling ps.AddCommand("...").InvokeAsync() multiple times on the same PowerShell instance, which meant that only the first command was executed and the second command was not executed at all (and hence no Stream data).

Is the correct (and best practice) to create a new PowerShell instance (with same runspace) for every command I want to invoke separately?