如何从C#中读取PowerShell脚本stdout和stderr [英] How to read PowerShell script stdout and stderr from C#
问题描述
我正在实现自定义PowerShell主机,我需要阅读PowerShell脚本的stdout和stderr.问题是,当我将通过调用管道返回的对象转换为字符串时,我没有得到stdout.但是,当我将"out-string" cmdlet添加到管道中时,它的工作原理非常好.有什么方法可以在不使用"out-string"的情况下获取stdout和stderror?
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.
推荐答案
PowerShell的 stdout
输出到另一个exe是通过获取对象并投影它们的字符串视图来合成的.PowerShell的本机输出是对象流.如果要使用这些对象的字符串版本,请使用 Out-String
.但是,从C#角度来看,直接处理PowerShell输出的对象通常更有用.
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.
对于 stderr
,您可以从 PowerShell.Streams.Error
属性读取ErrorRecords.如果您还希望这些字符串是人类可读的字符串,请在输出到用户之前,通过Out-String运行它们.
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.
这篇关于如何从C#中读取PowerShell脚本stdout和stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!