PowerShell tr​​y / catch /最终不适用于New-EventLog

时间:2019-01-30 22:26:46

标签: powershell try-catch

在我的PowerShell脚本之一中尝试try catch似乎出现了问题。我似乎无法在自己的程序段中捕获System.InvalidOperationException错误。我将不胜感激。

try {
    New-EventLog -LogName Application -Source "Update Service";
} catch [System.InvalidOperationException] {
    Write-Host "Error";
    Write-Host $Error[0].Exception;
} finally {
    $ErrorActionPreference = "Continue";
}

1 个答案:

答案 0 :(得分:0)

您无法捕捉到该异常,因为它首先不是InvalidOperationException

$ErrorActionPreference = 'Stop'
try {
    New-EventLog -LogName Application -Source 'Update Service'
} catch {
    $_.Exception.GetType().FullName   # Output: System.Exception
} finally{
    $ErrorActionPreference = 'Continue'
}