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

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

Powershellで直前に実行したコマンド実行エラーを出力してみました。

広告

直前に実行したコマンドのエラー情報を出力する

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

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

実行結果

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

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:\>

[参考] $Error のすべての情報を出力させる

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

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

実行結果

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

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をコピーしました