powershell - 将 stdout 和 stderr 捕获到文件,同时将它们保存在终端中
powershell - capture stdout and stderr to files while also keeping them in the terminal
我有一个脚本,它通过 Write-Output 和 Write-Error 进行记录,并调用许多其他脚本和可执行文件。
当我直接 运行 它时,我对我在终端中看到的内容感到满意。
但是我想另外将两个流捕获到两个单独的文件中,同时保持终端中的行为。
这很接近,但终端没有得到标准错误:
& .\main.ps1 2> stderr.log | Tee-Object -FilePath stdout.log
我考虑过 运行将其作为后台任务,但我担心我会很容易失去使用 Ctrl-C 组合它的能力。我的作品会被很多工程师使用,所以我不想引入意想不到的行为。
如果您能接受两个流都在一个文件中(基本上就像终端中的视图)这样的事实,那么这样做就可以了:
& .\main.ps1 2>&1 | Tee-Object -FilePath stdout_and_stderr.log
它将 stderr
重定向到 stdout
并像以前一样将其通过管道传输到 Tee-Object
。
# (Re)create the log files.
New-Item stdout.log, stderr.log -Force
# Merge the error stream (2) into the success stream (1) with 2>&1
# Then use the type of the objects to distinguish between
# error-stream output (whose objects are of type [System.Management.Automation.ErrorRecord])
# and success-stream output (all other types).
.\main.ps1 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) { $_ >> stderr.log }
else { $_ >> stdout.log }
$_ # pass through
}
注意:假设输出文件打开和关闭(通过 >>
附加)在每次迭代中,这个解决方案会很慢。
我有一个脚本,它通过 Write-Output 和 Write-Error 进行记录,并调用许多其他脚本和可执行文件。 当我直接 运行 它时,我对我在终端中看到的内容感到满意。 但是我想另外将两个流捕获到两个单独的文件中,同时保持终端中的行为。
这很接近,但终端没有得到标准错误:
& .\main.ps1 2> stderr.log | Tee-Object -FilePath stdout.log
我考虑过 运行将其作为后台任务,但我担心我会很容易失去使用 Ctrl-C 组合它的能力。我的作品会被很多工程师使用,所以我不想引入意想不到的行为。
如果您能接受两个流都在一个文件中(基本上就像终端中的视图)这样的事实,那么这样做就可以了:
& .\main.ps1 2>&1 | Tee-Object -FilePath stdout_and_stderr.log
它将 stderr
重定向到 stdout
并像以前一样将其通过管道传输到 Tee-Object
。
# (Re)create the log files.
New-Item stdout.log, stderr.log -Force
# Merge the error stream (2) into the success stream (1) with 2>&1
# Then use the type of the objects to distinguish between
# error-stream output (whose objects are of type [System.Management.Automation.ErrorRecord])
# and success-stream output (all other types).
.\main.ps1 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) { $_ >> stderr.log }
else { $_ >> stdout.log }
$_ # pass through
}
注意:假设输出文件打开和关闭(通过 >>
附加)在每次迭代中,这个解决方案会很慢。