【问题标题】:Redirecting stdout and stderr to file and console将 stdout 和 stderr 重定向到文件和控制台
【发布时间】:2020-11-28 10:07:52
【问题描述】:

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

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 重定向到stdout,这样我就会失去对错误的视觉印象。

【问题讨论】:

  • 这不是与stackoverflow.com/questions/24222088/… 重复吗?您想立即将输出发布到控制台吗?
  • @Clijsters 当program 运行很长时间时,最好有一些中间输出。但尽管如此,这是一个很好的解决方法。

标签: powershell io-redirection


【解决方案1】:

this blog post 获得提示,您可以编写一个自定义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

【讨论】:

    猜你喜欢
    • 2014-07-22
    • 2021-09-08
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    相关资源
    最近更新 更多