在 powershell 脚本中,我调用一个程序并想要重定向stdout
and stderr
to 不同的文件,同时仍然在控制台中显示两者的输出。所以基本上,我想要
stdout -> stdout
stdout -> out.log
stderr -> stderr
stderr -> err.log
到目前为止,我想出了这段代码,但不幸的是它只满足要求 1、2 和 4。Stderr 没有打印在屏幕上。
& program 2>"err.log" | Tee-Object -FilePath "out.log" -Append | Write-Host
我怎样才能打印stderr
也到控制台?自从写信给stderr
产生红色字体,我不想重定向stderr
to stdout
,从此我就失去了错误的视觉印象。
从中得到暗示这篇博文 https://blogs.msdn.microsoft.com/jenss/2013/02/14/powershell-stdout-go-out-stderr-go-everywhere/你可以写一个自定义的tee
按对象类型区分输入并写入相应的输出文件的函数。像这样的东西:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)