【问题标题】:Write-Error does not print to console before script exits在脚本退出之前写入错误不会打印到控制台
【发布时间】:2016-02-19 15:34:46
【问题描述】:

假设你有两个脚本,

outer.ps1

function Main()
{
    Write-Host "starting outer"
    TryRun "outer" {
        & $PSScriptRoot\inner.ps1
    }
}

Main

inner.ps1

function ThrowError()
{
    throw "Error"
}

function Main()
{
    Write-Host "starting inner"
    TryRun "inner" { 
        ThrowError 
    }
}

Main

其中TryRun在两者中的定义相同并定义为:

function TryRun([string] $name, [scriptblock] $action)
{
    try
    {
        $action.Invoke()
        Write-Host "'$name' successfully finished"

        Exit 0
    }
    catch [System.Exception]
    {
        $separator = New-Object string @("-", 120)
        Write-Error "'$name' failed`n$separator`n$($_.Exception.ToString())`n$separator"

        Exit 1
    }
}

现在,问题是,当你执行outer.ps1时,输出是:

starting outer
starting inner
<exception should have been printed here, but it was not>
'outer' successfully finished

但是,从inner.ps1 开始直接证明,它的行为符合预期:

TryRun : 'inner' failed
-------------------------------------------------------------------------------
-----------------------------------------
System.Management.Automation.RuntimeException: Error ---> 
System.Management.Automation.RuntimeException: Error
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(F
unctionContext funcContext, Exception exception)
   ...

更有趣的是 - 如果你将 Write-Error 更改为 Write-Host 并执行 outer.ps1 异常打印出来

在执行Exit 之前,我也尝试过刷新Console.Out, etc 缓冲区,但这没有帮助

现在,它为什么会这样? PS在退出前没有输出异常的原因是什么?调试会话显示它总是进入 catch 并执行 Write-Error

【问题讨论】:

  • 当您使用Invoke() 方法调用脚本块时,PowerShell 似乎忽略了错误流:{Write-Error Test}.Invoke()

标签: powershell


【解决方案1】:

原因是因为您在脚本块上使用 .invoke()。 .invoke() 返回 PSObject 的集合。据我了解,写入输出管道的所有数据都会返回给调用者;例如:{"a"}.invoke() 将返回 "a" ,但是,由于某种原因,错误管道的内容被吃掉或丢弃(不知道为什么??)。

您可以使用呼叫运算符&amp; 修复您的脚本。因此,将outer.ps1 中的$action.Invoke() 更改为&amp; $action 应该可以解决您的问题。

注意:您仍然应该能够使用$error.invoke() 中出现错误,例如 - {write-error "a"}.invoke(); $error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    相关资源
    最近更新 更多