Powershell v2:
try { Remove-Item C:\hiberfil.sys -ErrorAction Stop }
catch [System.IO.IOException]
{ "problem" }
catch [System.Exception]
{ "other" }
当然,我正在使用休眠文件作为示例。实际上还有另一个文件,我希望有时候我可能没有权限删除,我想抓住这种特殊情况。
输出:
output
然而$error[0] | fl * -Force
输出System.IO.IOException: Not Enough permission to perform operation.
问题:我不明白为什么我没有用我的第一个catch块捕获此异常,因为这与异常类型匹配。
答案 0 :(得分:7)
使用“停止”操作时,PowerShell会将例外类型更改为:
[System.Management.Automation.ActionPreferenceStopException]
所以这就是你应该抓住的东西。你也可以把它留下来并抓住所有类型。 如果你想对不同的不同观点进行操作,试一试:
try
{
Remove-Item C:\pagefile.sys -ErrorAction Stop
}
catch
{
$e = $_.Exception.GetType().Name
if($e -eq 'ItemNotFoundException' {...}
if($e -eq 'IOException' {...}
}
答案 1 :(得分:0)
我喜欢用于全局错误处理的Trap方法,因为如果发生未处理的异常以避免损坏我的数据,我想停止我的脚本。我将ErrorActionPreference设置为全面停止。然后我在我可能希望看到错误的地方使用Try / Catch来阻止它们停止脚本。在此处查看我的问题Send an email if a PowerShell script gets any errors at all and terminate the script