0

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!

Börg
  • 532
  • 1
  • 4
  • 13
  • Interesting. I'm not able to reproduce this when referencing `System.Management.Automation.dll` on Win10 directly - I get the message in both cases. What (version of the) SDK package are you using? – Mathias R. Jessen Sep 14 '20 at 11:20

1 Answers1

0

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?

Börg
  • 532
  • 1
  • 4
  • 13