我的PowerShell异常没有被抓住 [英] My PowerShell exceptions aren't being caught

查看:150
本文介绍了我的PowerShell异常没有被抓住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershell v2:

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

c $ c> $ error [0] | fl * -Force 输出 System.IO.IOException:没有足够的执行权限。

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

问题:我不明白为什么我没有捕获这个异常与我的第一个catch块,因为这符合异常类型。

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

推荐答案

当您使用Stop操作PowerShell将异常的类型更改为:

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

[System.Management.Automation.ActionPreferenceStopException]

所以这是你应该抓到的。你也可以把它留下来,抓住所有的类型。
如果你想对不同的excideptions进行操作,请尝试一下:

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' {...}
}

这篇关于我的PowerShell异常没有被抓住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆