powershell捕获[System.Management.Automation.MethodException]错误

powershell捕获[System.Management.Automation.MethodException]错误,powershell,throw,catch-block,Powershell,Throw,Catch Block,在powershell中,在特定条件下,我会执行以下操作: throw [System.Management.Automation.MethodException] 后来我钓到了这样的鱼: catch [System.Management.Automation.MethodException] { catch { 我的代码属于第二个(一般)陷阱。 当我在第二个catch中看到$\异常时,它说“System.Management.Automation.MethodException”-那么为

在powershell中,在特定条件下,我会执行以下操作:

throw [System.Management.Automation.MethodException]
后来我钓到了这样的鱼:

catch [System.Management.Automation.MethodException]
{

catch
{
我的代码属于第二个(一般)陷阱。 当我在第二个catch中看到$\异常时,它说“System.Management.Automation.MethodException”-那么为什么Powershell在第一个catch中没有捕捉到它呢? 我怎样才能解决这个问题


谢谢你,彼得

佩瑟拉尔在评论中说得对;您需要创建
MethodException
类的实例

他的建议既好又简洁:

throw [System.Management.Automation.MethodException]::new()
但它只适用于PowerShell 5+。在早期版本中:

$ex = New-Object -TypeName System.Management.Automation.MethodException
throw $ex
或者,在包含消息的任何版本中使用此选项的简单方法是将
[String]
作为例外:

throw [System.Management.Automation.MethodException]"You messed up."

throw[System.Management.Automation.MethodException]
->
throw[System.Management.Automation.MethodException]::new()