4
3

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

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

$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

#参考
http://stackoverflow.com/questions/21176487/adding-a-timeout-to-batch-powershell

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?