我的PowerShell异常没有被捕获

nor*_*ben 3 powershell exception-handling powershell-2.0

Powershell v2:

try { Remove-Item C:\hiberfil.sys -ErrorAction Stop }
catch [System.IO.IOException]
{ "problem" }
catch [System.Exception]
{ "other" }
Run Code Online (Sandbox Code Playgroud)

当然,我正在使用休眠文件作为示例.实际上还有另一个文件,我希望有时候我可能没有权限删除,我想抓住这种特殊情况.

输出:

output
Run Code Online (Sandbox Code Playgroud)

然而$error[0] | fl * -Force输出System.IO.IOException: Not Enough permission to perform operation.

问题:我不明白为什么我没有用我的第一个catch块捕获此异常,因为这与异常类型匹配.

Sha*_*evy 7

使用"停止"操作时,PowerShell会将异常类型更改为:

[System.Management.Automation.ActionPreferenceStopException]
Run Code Online (Sandbox Code Playgroud)

所以这就是你应该抓住的东西.你也可以把它留下来并抓住所有类型.如果你想对不同的排除做法,试一试:

try 
{
    Remove-Item C:\pagefile.sys -ErrorAction Stop
}
catch
{
    $e = $_.Exception.GetType().Name

    if($e -eq 'ItemNotFoundException' {...}
    if($e -eq 'IOException' {...}
}
Run Code Online (Sandbox Code Playgroud)