3

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.

1
  • Can you please elaborate on the output you currently get and what you are expecting? Commented Feb 7, 2014 at 19:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.