2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[小ネタ]PowerShell のエラー内容をログに書く

Posted at

メモ。

参考

本文

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) 

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?