メモ。
参考
本文
ErrorVariable
を使うとエラーを変数に格納出来るのでこれを使う。
例えば以下のように実行すると失敗するコマンドがある。
PS C:\> Stop-Process -Name invalidprocess
Stop-Process : Cannot find a process with the name "invalidprocess". Verify the process name and call the cmdlet again.
At line:1 char:1
+ Stop-Process -Name invalidprocess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (invalidprocess:String) [Stop-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.StopProcessCommand
この時のエラーを変数に格納するために コマンド実行時に -ErrorVariable
を指定しつつ、out-file
でファイルへ内容を書き出す。
test.ps1
# 変数を宣言
$errvar
Try {
# エラー時に停止するように指定
$ErrorActionPreference = 'Stop'
# エラーを発生させる。エラーは errvar に記載する
Stop-Process -Name invalidprocess -ErrorVariable errvar
}
Catch {
# 失敗したので終了ステータスコード1で終わらせる
exit 1;
}
Finally {
# ログにエラーを書き出す
$time=Get-Date
"Attempted to run script at $time with error $errvar " | out-file C:\temp\scriptExec.log -Append
}
ファイルにはエラー内容が書き込む事ができる
\temp\scriptExec.log
Attempted to run script at 03/31/2019 06:37:33 with error System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find a process with the name "invalidprocess". Verify the process name and call the cmdlet again.
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)