My PowerShell exceptions aren't being caught

六月ゝ 毕业季﹏ 提交于 2019-12-21 05:32:16

问题


Powershell v2:

try { Remove-Item C:\hiberfil.sys -ErrorAction Stop }
catch [System.IO.IOException]
{ "problem" }
catch [System.Exception]
{ "other" }

I'm using the hibernation file as an example, of course. There's actually another file that I expect I may not have permission to delete sometimes, and I want to catch this exceptional situation.

Output:

output

and yet $error[0] | fl * -Force outputs System.IO.IOException: Not Enough permission to perform operation.

Problem: I don't see why I'm not catching this exception with my first catch block, since this matches the exception type.


回答1:


When you use the Stop action PowerShell changes the type of the exception to:

[System.Management.Automation.ActionPreferenceStopException]

So this is the what you should catch. You can also leave it out and catch all types. Give this a try if you want to opearte on different excdeptions:

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

    if($e -eq 'ItemNotFoundException' {...}
    if($e -eq 'IOException' {...}
}



回答2:


I like the Trap method for global error handling, as I wanted to stop my scripts if unhandled exceptions were occurring to avoid corrupting my data. I set ErrorActionPreference to stop across the board. I then use Try/Catch in places where I may expect to see errors in order to stop them halting the scripts. See my question here Send an email if a PowerShell script gets any errors at all and terminate the script



来源:https://stackoverflow.com/questions/14648590/my-powershell-exceptions-arent-being-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!