0
0

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 3 years have passed since last update.

PowerShellのスクリプトにTimeoutを設定する

Posted at

PowerShell内の処理せず残り続けることを避けるためにTimeoutを設定し、一定時間経過後に終了させる方法です。

外部から受け取った引数を変数に設定

 Param($Arg1, $Arg2)

処理したい内容をfunctionとして記述

 $function_hogehoge = {
 Param($Arg1, $Arg2)
   処理の内容を記載する
 }

タイムアウトの設定(秒)

 $timeOut = 30

Jobの実行、引数を設定

 $job = Start-Job -ScriptBlock $function_hogehoge -ArgumentList $Arg1, $Arg2

timeOutで指定した時間の経過後は、Jobを終了する。

 Wait-Job -Job $job -Timeout $timeoutSeconds | Out-Null

 if($job.State -eq "Completed"){
  "正常終了"
 }elseif($job.State -eq "Running"){
  "まだ実行中"
 }elseif($job.State -eq "Failed"){
  "失敗"
 }

状態に関係なく強制終了

 Remove-Job -Force $job

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?