LoginSignup
3
2

More than 5 years have passed since last update.

[PowerShell]コマンドの実行にタイムアウトを設定する

Posted at

一定時間以上経過したら強制的にコマンドを終了させるには、以下のようにします。

$timeoutSeconds = 5    #タイムアウトの秒数

$j = Start-Job {
    #ここに時間がかかりそうなコマンドを記述する
    Get-ChildItem *
}

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

if($j.State -eq "Completed"){
    "完了!"
    Receive-Job $j    #結果を出力する
}elseif($j.State -eq "Running"){
    "中断"
}elseif($j.State -eq "Failed"){
    "例外発生"
}

Remove-Job -force $j    #cleanup

参考

関連記事

[PowerShell]Start-Jobで共通の関数を使う
[PowerShell]Start-Jobのスクリプトブロックでの例外を取得する

3
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
3
2