PowerShell的V2:
try { Remove-Item C:\hiberfil.sys -ErrorAction Stop }
catch [System.IO.IOException]
{ "problem" }
catch [System.Exception]
{ "other" }
我使用的休眠文件作为一个例子,当然。 实际上,有,我希望我可能没有权限有时删除其他文件,我想抓住这个特殊情况。
输出:
output
然而$error[0] | fl * -Force
$error[0] | fl * -Force
输出System.IO.IOException: Not Enough permission to perform operation.
问题:我不明白为什么我没有赶上这个例外,我的第一个catch块,因为这种异常类型相匹配。
当您使用停止动作PowerShell的改变例外的类型:
[System.Management.Automation.ActionPreferenceStopException]
所以,这是你应该抓住什么。 您也可以离开它,并捕获所有类型。 如果你想opearte不同excdeptions试试这个:
try
{
Remove-Item C:\pagefile.sys -ErrorAction Stop
}
catch
{
$e = $_.Exception.GetType().Name
if($e -eq 'ItemNotFoundException' {...}
if($e -eq 'IOException' {...}
}
我喜欢全局错误处理的陷阱的方法,因为我想阻止我的剧本,如果未处理的异常正在发生,以避免破坏我的数据。 我设置ErrorActionPreference全线停止。 然后我用的try / catch在地方,我可能会看到以错误阻止他们停止脚本。 见我的问题在这里发送电子邮件,如果PowerShell脚本都得到任何错误,并终止脚本