Reputation: 383
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.
Upvotes: 3
Views: 2397
Reputation: 201602
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.
Upvotes: 4