はじめに
最近PowerShellにハマっている私ですが、bash
・zsh
で言うところのset -x
(set -o xtrace
)をPowerShellでもやりたいなと思いました。
今回はそのやり方を紹介したいと思います。
その前に
set -x
(set -o xtrace
)を用いることで実行される各コマンドが標準出力に表示されます。
Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
// DeepL翻訳
単純なコマンド、for コマンド、case コマンド、select コマンド、算術演算のトレースを、コマンドとその引数または関連する単語リストが展開された後、実行される前に表示する。PS4変数の値が展開され、その結果の値がコマンドと展開された引数の前に出力される。
The Set Builtin (Bash Reference Manual)
#!/bin/bash # デバッグトレースを有効にする set -x echo "Debugging this script" variable="example" echo $variable # デバッグトレースを無効にする set +x
↓
# bashでset -xをしたサンプル $ ./sandbox.bash + echo 'Debugging this script' Debugging this script + variable=example + echo example example + set +x
PowerShellでデバッグトレースを有効にする方法
PowerShellでset -x
と同様の機能を実現するには、Set-PSDebug -Trace 1
を使用します。これにより、スクリプトの各コマンドが実行される前に表示されるようになります。
# デバッグトレースを有効にする Set-PSDebug -Trace 1 Write-Output "Debugging this script" $variable = "example" Write-Output $variable # デバッグトレースを無効にする Set-PSDebug -Trace 0
↓
# pwshでset -xと同じようにデバッグトレースを有効にしたサンプル > ./sandbox.ps1 DEBUG: 6+ >>>> Write-Output "Debugging this script" Debugging this script DEBUG: 7+ >>>> $variable = "example" DEBUG: 8+ >>>> Write-Output $variable example DEBUG: 11+ >>>> Set-PSDebug -Trace 0