无法从Get-PSDrive中捕获DriveNotFoundException

Dou*_* R. 3 powershell

我无法在以下示例中捕获DriveNotFoundException生成Get-PSDrive的内容:

try {
    # Assumes no Q:\ drive connected.
    $foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.DriveNotFoundException] {
    Write-Output "Drive not found."
}
catch {
    Write-Output "Something else went wrong."
}
Run Code Online (Sandbox Code Playgroud)

这应该打印以下内容:

PS C:\temp> .\foo.ps1
Drive not found.
PS C:\temp>
Run Code Online (Sandbox Code Playgroud)

相反,我得到:

PS C:\temp> .\foo.ps1
Something else went wrong.
PS C:\temp>
Run Code Online (Sandbox Code Playgroud)

我正在使用Powershell 2.0,如果这是相关的.

HAL*_*256 5

问题是因为-ErrorAction Stop正在改变try/catch块所看到的Exception类型.

您可以通过捕捉ActionPreferenceStopException类型来证明它.因此,让我们运行一些故障排除代码,看看发生了什么:

try {
    # Assumes no Q:\ drive connected.
    $foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.DriveNotFoundException] {
    Write-Output "Drive not found."
}
catch [System.Management.Automation.ActionPreferenceStopException] {
    Write-Output "Stop Exception."
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
catch
{
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
Run Code Online (Sandbox Code Playgroud)

这将返回以下输出:

Stop Exception.
Caught an exception:
Exception Type: System.Management.Automation.DriveNotFoundException
Exception Message: Cannot find drive. A drive with the name 'Q' does not exist.
Run Code Online (Sandbox Code Playgroud)

所以,你看到的try/catch抓住了[System.Management.Automation.ActionPreferenceStopException]例外,即使在异常类型 [System.Management.Automation.DriveNotFoundException] 里面的catch块.

因此,我们可以使用@ haliphax解决方案的略微修改版本来处理它,这是检查ActionPreferenceStopExceptioncatch块内的错误类型:

try {
    # Assumes no Q:\ drive connected.
    $foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.ActionPreferenceStopException] {
    if ($Error[0].Exception.GetType().Name -eq 'DriveNotFoundException') {
        Write-Output "Drive not found."
    }
    else {
        Write-Output "Something else went wrong."
    }
}
catch {
    Write-Output "Something else went wrong."
}
Run Code Online (Sandbox Code Playgroud)