简体   繁体   English

如何从C#中读取PowerShell脚本stdout和stderr

[英]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. 我正在实现自定义PowerShell主机,我需要读取PowerShell脚本的stdout和stderr。 Problem is that I do not get stdout when I convert object returned by invoking pipeline to string. 问题是当我将通过调用管道返回的对象转换为字符串时,我没有得到stdout。 However, when I add "out-string" cmdlet to the pipeline it works perfectly fine. 但是,当我向管道添加“out-string”cmdlet时,它可以正常工作。 Is there any way to fetch stdout and stderror without using "out-string"? 有没有办法在不使用“out-string”的情况下获取stdout和stderror?

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. 当我使用上面的代码时,我只得到部分stdout。

PowerShell's stdout output to another exe is synthesized by taking objects and projecting a string view of them. PowerShell的stdout输出到另一个exe是通过获取对象并投影它们的字符串视图来合成的。 PowerShell's native output is a stream of objects. PowerShell的本机输出是一个对象流。 If you want to a string version of those objects then use Out-String . 如果您想要这些对象的字符串版本,请使用Out-String However, from a C# perspective it is often more useful to deal directly with the objects that PowerShell outputs. 但是,从C#的角度来看,直接处理PowerShell输出的对象通常更有用。

For stderr , you can read ErrorRecords from the PowerShell.Streams.Error property. 对于stderr ,您可以从PowerShell.Streams.Error属性中读取ErrorRecords。 If you want a human readable string for those as well, run them thru Out-String before outputting to your user. 如果您还需要一个人类可读的字符串,请在输出到您的用户之前通过Out-String运行它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM