代码改变世界

PowerShell: capture console output to log file 使用PowerShell导出控制台输出

2017-11-16 19:35  mengmz  阅读(1151)  评论(0编辑  收藏  举报

在运行程序时需要将Console中间结果输出来,方便后续的查看,在Windows上使用PowerShell进行。

主要使用Start-TranscriptStop-Transcript命令,但在细节上需要注意。

我在PowerShell中运行另一个可执行程序 fortran_test.exe,在使用了Start-Transcript 后只记录了命令,却没有记录该程序输出的中间信息,同样的问题也出现在运行CFD程序时,原以为记录了完整的输出信息,但是最后只记录了部分输出信息或者干脆为空,我对于这点非常的不理解,最终看到了这篇文章Workaround for Start-Transcript on native processes ,以及另外一篇博客 PowerShell: capturing output to log file and console,找到了解决方案及原因:

fortran_test.exe被认为是native console application, 其输出一般是控制台缓冲区,因此PowerShell不对其输出进行处理,那如何处理这种情况呢?

Start-Transcript 
ipconfig  
Stop-Transcript

变为

Start-Transcript  
ipconfig | Out-Default 
Stop-Transcript

其中,关键的部分是 Out-Default 命令,参见 Out-Default ,参考文章2中使用的命令为Out-Host ,其实二者相同,因为Out-Host 就是默认的设置。