【问题标题】:Powershell : how to redirect stdout and stderr to file and console separatelyPowershell:如何将标准输出和标准错误分别重定向到文件和控制台
【发布时间】:2019-11-17 13:33:56
【问题描述】:
如何在 PowerShell 中将 stdout 和 stderr 重定向到文件和控制台分别?
翻遍所有网站,我发现基本上有两种方法,但都不能完全满足要求
& .\test.ps1 2>&1 | tee .\out.txt
在这种情况下,stdout 和 stderr 仍然可以在控制台上显示,但它们会被合并到在同一个文件中
& .\test.ps1 2>error.txt | tee out.txt
这是我从SilverNak 看到的解决方法。但是正如他所说,stderr 不会显示在控制台上
【问题讨论】:
标签:
powershell
stderr
io-redirection
tee
【解决方案1】:
要在控制台中同时显示成功输出和错误流输出并将其捕获到特定于流的文件中,需要额外的工作:
# Create / truncate the output files
$null > out.txt
$null > error.txt
# Call the script and merge its output and error streams.
& .\test.ps1 2>&1 | ForEach-Object {
# Pass the input object through (to the console).
$_
# Also send the input object to the stream-specific output file.
if ($_ -is [System.Management.Automation.ErrorRecord]) { $_ >> error.txt }
else { $_ >> out.txt }
}