将stdout和stderr重定向到文件和控制台 [英] Redirecting stdout and stderr to file and console

查看:173
本文介绍了将stdout和stderr重定向到文件和控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在powershell脚本中,我调用一个程序,并希望将stdoutstderr重定向到不同的文件,同时仍在控制台中显示这两个文件的输出.所以基本上,我要

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.

推荐答案

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重定向到文件和控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆