How to read PowerShell script stdout and stderr from C#

橙三吉。 提交于 2021-01-27 14:58:58

问题


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:


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.



来源:https://stackoverflow.com/questions/21635541/how-to-read-powershell-script-stdout-and-stderr-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!