Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read PowerShell script stdout and stderr from C#

I'm implementing a custom PowerShell host and I need to read stdout and stderr of the PowerShell script. Problem is that I do not get stdout when I convert object returned by invoking pipeline to string. However, when I add "out-string" cmdlet to the pipeline it works perfectly fine. Is there any way to fetch stdout and stderror without using "out-string"?

this.currentPowerShell.AddScript(cmd);
Collection<PSObject> results = this.currentPowerShell.Invoke();
foreach (PSObject obj in results)
{
      Console.WriteLine(obj.ToString());
}

When I use the code above I only get partial stdout.

like image 580
AccurateEstimate Avatar asked Feb 10 '26 19:02

AccurateEstimate


1 Answers

PowerShell's stdout output to another exe is synthesized by taking objects and projecting a string view of them. PowerShell's native output is a stream of objects. If you want to a string version of those objects then use Out-String. However, from a C# perspective it is often more useful to deal directly with the objects that PowerShell outputs.

For stderr, you can read ErrorRecords from the PowerShell.Streams.Error property. If you want a human readable string for those as well, run them thru Out-String before outputting to your user.

like image 57
Keith Hill Avatar answered Feb 13 '26 10:02

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!