MSHのデバッグ手法(6)
「Trap」構文を利用して例外処理を実装する場合、通常、Trap対象とする例外クラスの指定が必要です。*1
そのため、スクリプトでエラーが発生した時に、例外クラスの名前がすぐに分かると便利です。
発生した例外クラス名を調べる
get-exception.msh
param([int]$index=0) if($error.count -ne 0) { # インデックスが範囲外の場合は処理しない if($index -gt $error.count - 1) {return} $thisError = $error[$index] if ($thisError -is [System.Management.Automation.RuntimeException]) { $thisError.InnerException.GetType().FullName } elseif ($thisError -is [System.Management.Automation.ErrorRecord]) { $thisError.CategoryInfo } }
利用方法
get-exception [index]
- 例外クラスの情報を取得します。
- [index]は$errorのindexです。
- 「0」→最後に発生した例外クラスの情報を取得
- 「1」→最後から2番目に発生した例外クラスの情報を取得
- [index]を省略するとデフォルト値の「0」が使われます。
RuntimeExceptionの例
MSH C:\> 1/0 Attempted to divide by zero. At line:1 char:3 + 1/0 <<<< MSH C:\> get-exception System.DivideByZeroException
ErrorRecordの例
MSH C:\> set-location z: set-location : Cannot find drive. A drive with name 'z' does not exist. At line:1 char:13 + set-location <<<< z: MSH C:\> get-exception Category : ObjectNotFound Activity : set-location Reason : DriveNotFoundException TargetName : z TargetType : String
*1:例外クラスを指定しない記述も可能です。その場合、全ての例外を捕捉してしまうため、細かな制御はできません。