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
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
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.
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
}
}
}
which could be used like this:
& program.exe 2>&1 | Tee-Custom -OutputLogfile 'out.log' -ErrorLogfile 'err.log' -Append
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With