Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting stdout and stderr to file and console

Tags:

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.

like image 924
SilverNak Avatar asked Sep 06 '17 11:09

SilverNak


1 Answers

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
like image 87
Ansgar Wiechers Avatar answered Oct 07 '22 01:10

Ansgar Wiechers