【问题标题】:Powershell: Throwing Exception in Catch block terminates but does not output Exception to consolePowershell:在 Catch 块中引发异常终止但不向控制台输出异常
【发布时间】:2020-08-23 03:43:55
【问题描述】:

我最近开始遇到这个奇怪的问题,我的异常在我的 catch 块中被捕获,但是在重新抛出时它会终止脚本(如预期的那样),但不会将重新抛出的异常写入控制台。我不关心正在抛出的特定异常,我只关心重新抛出异常并将堆栈跟踪输出到控制台。我正在使用 PowerShell 4。

try {
    $variable1 = 'value1'
    $variable2 = 'value2'
    [string[]]$variable3 = 'value3'

    [Collections.Generic.List[Microsoft.PowerShell.Commands.MatchInfo]]$matches = New-Object Collections.Generic.List[Microsoft.PowerShell.Commands.MatchInfo]
    $matches = `
        Get-Matches `
            -Param1 $variable1 `
            -Param2 $variable2 `
            -Param3 $variable3 `
            -Silent $true

    Write-Host `n`nTotal Matches Found: $matches.Count
} catch {
    throw $_
}

我还尝试对 catch 块进行以下更改:

} catch {
    throw
}
} catch {
    throw $_.Exception
}
} catch {
    throw $_.Exception.Message
}
} catch {
    throw $error[0].Exception
}
} catch {
    throw $error[0].Exception.Message
}

【问题讨论】:

  • Get-Matches 是做什么的?由于它是您正在使用的一些客户 cmdlet/功能,我们不知道会发生什么。代码在哪里?
  • 一方面,不要使用变量名$matches作为自定义变量,因为它是PowerShell中的Automatic variable。
  • @postanote,Get-Matches 在做什么重要吗?我不关心抛出了什么异常(这是一个类型转换错误),我关心的是根据 Microsoft 文档在 catch 块中抛出的异常。 Get-Matches 返回其结果后抛出异常,并将该结果分配给变量 $matches 时失败。
  • @Theo,感谢您提供的信息。我不认为这是我问题的根源,但这绝对是有用的信息。

标签: powershell exception try-catch powershell-4.0


【解决方案1】:

要将异常输出到您的 catch 块中的屏幕,请使用以下命令:

try {
    #code
} catch {
    #handle exception
    Write-Output $_.Exception.Message
} 

此外,您的 throw 应该在您的 try 语句中。在 catch 块内抛出异常是没有意义的,因为已经抛出异常并被捕获到那里!

try {
    #code
    if($something -ne $right) {
        throw "Something isn't right!" 
    } 
} catch {
    #handle exception
    Write-Output $_.Exception.Message
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    相关资源
    最近更新 更多