在powershell中重定向外部DLL的输出

时间:2015-10-13 19:27:17

标签: c# powershell dll

我有一个处理xml文件的C#程序集,最后将结果吐出到控制台 例如Console.WriteLine(_header.ToString());
我可以在powershell中加载这个dll并调用正确的方法:

[sqlproj_doctor.sqlprojDoctor]::ProcessXML($file) | out-file ./test.xml

一切都很好。

当我想重定向输出时问题就开始了。出于某种原因,stdout是空的。我错过了什么?我需要进一步处理这个dll的输出。

注意:如果我编译与可执行文件相同的代码,它会正确填充标准输出流,我可以重定向输出。

另一个注意事项:作为一种解决方法,我将方法从void更改为string,现在可以操作返回的字符串。

1 个答案:

答案 0 :(得分:2)

当您调用[Console]::WriteLine('SomeText')时,它会写入PowerShell进程标准输出,而不是命令输出,因此无法通过标准PowerShell运算符从同一PowerShell进程内重定向,如下所示:

[Console]::WriteLine('SomeText')|Out-File Test.txt

您必须生成新的PowerShell流程,并重定向该新流程的输出:

powershell -Command "[Console]::WriteLine('SomeText')"|Out-File Test.txt

如果某些命令使用[Console]::WriteLine写入控制台,您可以捕获该输出而无需启动新的PowerShell实例:

$OldConsoleOut=[Console]::Out
$StringWriter=New-Object IO.StringWriter
[Console]::SetOut($StringWriter)

[Console]::WriteLine('SomeText') # That command will not print on console.

[Console]::SetOut($OldConsoleOut)
$Results=$StringWriter.ToString()
$Results # That variable would contain "SomeText" text.

虽然如果命令不使用[Console]::WriteLine,但如果直接写入stdout流,则无效:

$OldConsoleOut=[Console]::Out
$StringWriter=New-Object IO.StringWriter
[Console]::SetOut($StringWriter)

$Stdout=[Console]::OpenStandardOutput()
$Bytes=[Console]::OutputEncoding.GetBytes("SomeText"+[Environment]::NewLine)
$Stdout.Write($Bytes,0,$Bytes.Length) # That command will print on console.
$Stdout.Close()

[Console]::SetOut($OldConsoleOut)
$Results=$StringWriter.ToString()
$Results # That variable will be empty.