2016-08-26 23 views
1

は、一定の条件の下で、私はこれを行う:PowerShellのキャッチPowerShellで[System.Management.Automation.MethodException]エラー

throw [System.Management.Automation.MethodException] 

後、私はこのようなキャッチがあります。

catch [System.Management.Automation.MethodException] 
{ 

catch 
{ 

私のコードの滝を第2の(一般的な)漁獲物に入る。 私は$ _を見ていますが、2番目のキャッチの例外は、 'System.Management.Automation.MethodException'と表示されます。なぜPowershellが最初のキャッチでそれをキャッチしないのですか? これをどのように修正できますか?

ありがとう、Peter

+1

'[System.Management.Automationを投げます。メソッド例外] - > 'throw [System.Management.Automation.MethodException] :: new()' – PetSerAl

答えて

1

PetSerAlがコメントに正しくあります。 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."