7

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.

SilverNak
  • 3,283
  • 4
  • 28
  • 44
  • Isn't this a duplicate to https://stackoverflow.com/questions/24222088/powershell-capture-program-stdout-and-stderr-to-separate-variables ? Do you want to post the output _immediately_ to the console? – Clijsters Sep 06 '17 at 12:13
  • 1
    @Clijsters When `program` runs a long time, it could be good to have some intermediate output. But nontheless, this is a good workaround. – SilverNak Sep 07 '17 at 12:22

1 Answers1

5

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328