Powershellコマンド実行時のエラーを出力してみた

Powershell Powershell
この記事は約5分で読めます。

Powershellコマンド実行時にエラーとなる場合、手動で実行した場合には標準出力にエラー内容が表示されます。

しかし、Powershellスクリプトとタスクスケジューラを組み合わせて毎日自動実行するなど手動以外の方法でPowershellを実行する場合にエラーとなったとき、エラー内容が分からないと原因を特定できずに困ります

そこで、Powershellコマンド実行時エラーを出力するということを試してみました。

広告

1.Powershellコマンドのエラー情報を出力する

$Error に格納されている情報を出力させればOKです。

try {
    # 意図的にエラーを発生
  1/0
} catch {
    # 直前のエラーの詳細を取得
    Write-Output "ErrorMessage : $($_.Exception.Message)"
    Write-Output "ErrorType : $($_.Exception.GetType().FullName)"
    Write-Output "ErrorLocation : $($_.ScriptStackTrace)"
}

1-1.実行結果

以下のようにエラーの内容を出力できます。

PS C:\> powershell -ExecutionPolicy Unrestricted -File ./output_error.ps1
ErrorMessage : 0 で除算しようとしました。
ErrorType : System.Management.Automation.RuntimeException
ErrorLocation : <ScriptBlock>、C:\output_error.ps1: 行 3
PS C:\>

2.$Error のすべての情報を出力させる

上記では出力させる情報を絞りましたが、$Error のすべての情報を出力させることも可能です。

try {
    # 意図的にエラーを発生
    kwb9gmeinayenvbayhbabgaua
} catch {
    # エラーの詳細をすべて表示
    Write-Output "ErrorDetailsBelow" ($Error[0] | Format-List -Force)
}

2-1.実行結果

以下のようにエラーの詳細の内容を出力できます。

PS C:\> powershell -ExecutionPolicy Unrestricted -File ./output_all_error.ps1
ErrorDetailsBelow


Exception             : System.Management.Automation.CommandNotFoundException: 用語 'kwb9gmeinayenvbayhbabgaua' は、コマンドレット、関数、スクリプト ファイル、
                        または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、パスが含まれている場合はそのパスが正しいこ
                        とを確認してから、再試行してください。
                           場所 System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           場所 System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           場所 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           場所 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : kwb9gmeinayenvbayhbabgaua
CategoryInfo          : ObjectNotFound: (kwb9gmeinayenvbayhbabgaua:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : <ScriptBlock>、C:\output_all_error.ps1: 行 3
PipelineIterationInfo : {}
PSMessageDetails      :



PS C:\>
タイトルとURLをコピーしました