簡単な説明
終了エラーを生成する throw キーワードについて説明します。
長い説明
throw キーワードを指定すると、終了エラーが発生します。
throw キーワードを使用して、コマンド、関数、またはスクリプトの処理を停止できます。
たとえば、throw ステートメントのスクリプト ブロック内の if キーワードを使用して、条件に応答したり、catchtry-catch- ステートメントの finally ブロックに応答したりできます。
throwキーワードは、ユーザー メッセージ文字列やエラーの原因となったオブジェクトなど、任意のオブジェクトをスローできます。
構文
throw キーワードの構文は次のとおりです。
throw [<expression>]
throw構文の式は省略可能です。
throw ステートメントがcatch ブロックに表示されておらず、式が含まれていない場合は、ScriptHalted エラーが生成されます。
throw
ScriptHalted
At line:1 char:6
+ throw <<<<
+ CategoryInfo : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted
throw キーワードが式のないcatch ブロックで使用されている場合は、現在の RuntimeException が再度スローされます。 詳細については、「 about_Try_Catch_Finally」を参照してください。
文字列のスロー
次の例に示すように、 throw ステートメントの省略可能な式には文字列を指定できます。
throw "This is an error."
This is an error.
At line:1 char:6
+ throw <<<< "This is an error."
+ CategoryInfo : OperationStopped: (This is an error.:String) [], R
untimeException
+ FullyQualifiedErrorId : This is an error.
他のオブジェクトをスローする
式には、次の例に示すように、PowerShell プロセスを表すオブジェクトをスローするオブジェクトを指定することもできます。
throw (Get-Process pwsh)
At line:1 char:6
+ throw <<<< (Get-Process powershell)
+ CategoryInfo : OperationStopped: (System.Diagnostics.Process (Pow
erShell):Process) [],
RuntimeException
+ FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)
自動変数の ErrorRecord オブジェクトの $Error プロパティを使用して、エラーを調べることができます。
$Error[0].TargetObject
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
319 26 61016 70864 568 3.28 5548 PowerShell
throw オブジェクトまたは .NET 例外をすることもできます。 次の例では、 throw キーワードを使用して、 System.FormatException オブジェクトをスローします。
$formatError = New-Object System.FormatException
throw $formatError
One of the identified items was in an invalid format.
At line:1 char:6
+ throw <<<< $formatError
+ CategoryInfo : OperationStopped: (:) [], FormatException
+ FullyQualifiedErrorId : One of the identified items was in an invalid
format.
結果のエラー
throw キーワードは、ErrorRecord オブジェクトを生成できます。
ErrorRecord オブジェクトの Exception プロパティには、RuntimeException オブジェクトが含まれています。
ErrorRecord オブジェクトと RuntimeException オブジェクトの残りの部分は、スローされるオブジェクトによって異なります。
throw オブジェクトは ErrorRecord オブジェクトにラップされ、ErrorRecord オブジェクトは自動的に$Error自動変数に保存されます。
throwを使用して必須パラメーターを作成する
PowerShell の過去のバージョンとは異なり、パラメーターの検証には throw キーワードを使用しないでください。 正しい方法については、 about_Functions_Advanced_Parameters を参照してください。
こちらも参照ください
PowerShell