MSHのデバッグ手法(1)
MSHは、デバッグのための仕組みが色々用意されています。
「$DebugPreference」と「Write-Deubg」
スクリプトの処理を一時停止させ、変数の値を確認するサンプルです。
MSH C:\> $DebugPreference = "Inquire" MSH C:\> $a = 0 MSH C:\> $b = 0 MSH C:\> while($a -lt 10) >> { >> $b += $a >> if($a -eq 5){Write-Debug $b} >> $a++ >> } >> DEBUG: 15 Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):
「$DebugPreference」はデバッグ時の振る舞いを定義する特殊変数です。
値の種類と意味は以下の通りです。
- SilentlyContinue(初期値)
- Debug情報を出力しない。
- Continue
- Debug情報を出力する。
- Inquire
- Debug情報を出力する。1Step毎に処理の実行を確認する。
- Stop
- Debug情報を出力する。処理を停止する。
サンプルでは「Inquire」を設定し、Write-Debug実行時に「ステップ実行モード」に切り替えています。
「Continue with this operation?」に対してSuspend[S]を選ぶと、
処理を一時停止したまま、コンソールに処理が戻るので、
自由にコマンドを実行できます。もちろん変数の値の確認も可能です。
では、Suspendして変数$aと$bの値を確認してみます。
MSH C:\> $DebugPreference = "Inquire" MSH C:\> $a = 0 MSH C:\> $b = 0 MSH C:\> while($a -lt 10) >> { >> $b += $a >> if($a -eq 5){Write-Debug $b} >> $a++ >> } >> DEBUG: 15 Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): S MSH C:\> $a 5 MSH C:\> $b 15 MSH C:\> exit Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): A MSH C:\>
- exitで元のスクリプトに処理が戻ります。