Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的PowerShell例外是';不要被抓住_Powershell_Exception Handling_Powershell 2.0 - Fatal编程技术网

我的PowerShell例外是';不要被抓住

我的PowerShell例外是';不要被抓住,powershell,exception-handling,powershell-2.0,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" } 当然,我以休眠文件为例。实际上还有一个文件,我希望我有时没有删除的权限,我想抓住这个例外情况 输出: output 然而$error[0]| fl*-Force输出System.IO.IOExce

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:没有足够的权限执行操作。


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

使用停止操作时,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' {...}
}

我喜欢全局错误处理的Trap方法,因为我希望在发生未处理的异常时停止脚本,以避免损坏数据。我将ErrorActionPreference设置为全面停止。然后,我在可能看到错误的地方使用Try/Catch,以阻止它们停止脚本。请看我的问题

啊,好的,这对错误偏好是有意义的。那么,
catch[exceptiontype]
语法是怎么处理的呢?根据,这就是解决方法…这就是处理终止异常的方法。您的操作是非终止的(这就是您指定erroraction停止的原因)。这就是为什么你必须使用shay的解决方案。顺便说一句,如果你看这篇文章,你会发现[System.Management.Automation.pArgumentException]的捕获不是打印的,而是其他值,比如[System.exception](我认为这是不必要的,因为所有的异常都属于这种类型。好的,这很有帮助。对于我关心的每个命令/函数,我将使用带有try/catch块的
-erroraction Stop
。脚本编写人链接实际上是: