问题描述
在powershell脚本中,我调用一个程序,并希望将stdout
和stderr
重定向到不同的文件,同时仍在控制台中显示这两个文件的输出.所以基本上,我要
In a powershell script, I call a program and want to redirect stdout
and stderr
to different files, while still showing the output of both in the console. So basically, I want
stdout -> stdout
stdout -> out.log
stderr -> stderr
stderr -> err.log
到目前为止,我想出了这段代码,但不幸的是,它仅满足要求1、2和4.Stderr尚未打印在屏幕上.
So far, I came up with this code, but unfortunately it only fulfils requirements 1, 2 and 4. Stderr is not printed on the screen.
& program 2>"err.log" | Tee-Object -FilePath "out.log" -Append | Write-Host
如何也将stderr
打印到控制台?由于写入stderr
会产生红色字体,因此我不想将stderr
重定向到stdout
,因为那样我会失去对该错误的视觉印象.
How can I print stderr
to the console also? Since writing to stderr
produces red typeface, I don't want to redirect stderr
to stdout
, since then I would lose the visual impression of the error.
推荐答案
从此博客文章,您可以编写一个自定义的tee
函数,该函数按对象类型区分输入并写入相应的输出文件.像这样:
Taking a cue from this blog post you could write a custom tee
function that distinguishes input by object type and writes to the corresponding output file. Something like this:
function Tee-Custom {
[CmdletBinding()]
Param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[array]$InputObject,
[Parameter(Mandatory=$false)]
[string]$OutputLogfile,
[Parameter(Mandatory=$false)]
[string]$ErrorLogfile,
[Parameter(Mandatory=$false)]
[switch]$Append
)
Begin {
if (-not $Append.IsPresent) {
if ($OutputLogfile -and (Test-Path -LiteralPath $OutputLogfile)) {
Clear-Content -LiteralPath $OutputLogfile -Force
}
if ($ErrorLogfile -and (Test-Path -LiteralPath $ErrorLogfile)) {
Clear-Content -LiteralPath $ErrorLogfile -Force
}
}
}
Process {
$InputObject | ForEach-Object {
$params = @{'InputObject' = $_}
if ($_ -is [Management.Automation.ErrorRecord]) {
if ($ErrorLogfile) { $params['FilePath'] = $ErrorLogfile }
} else {
if ($OutputLogfile) { $params['FilePath'] = $OutputLogfile }
}
Tee-Object @params -Append
}
}
}
可以这样使用:
& program.exe 2>&1 | Tee-Custom -OutputLogfile 'out.log' -ErrorLogfile 'err.log' -Append
这篇关于将stdout和stderr重定向到文件和控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!