0
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]Start-Jobのスクリプトブロックでの例外を取得する

Last updated at Posted at 2017-01-09

Start-Jobのスクリプトブロック内で例外が起きた場合、呼び出し側ではReceive-Jobするときに例外が発生します。

$sb = {
    #何らかの処理

    #例外発生
    throw
}

$j = Start-Job $sb
Wait-Job -Job $j | Out-Null

try {
    #Receive-Jobで例外が発生する
    Receive-Job $j -ErrorAction Stop
}
catch {
    "catch"
}

Remove-Job $j
output
hoge
catch

Receive-Jobする前に例外が起きたかどうかを確認するには、JobのStateの値を確認します。
例外が発生するとFailed、正常に終了したならCompletedになります。

$sb = {
    #何らかの処理

    #例外発生
    throw
}

$j = Start-Job $sb
Wait-Job -Job $j | Out-Null

#JobのStateを取得する
$jobState = $j.State

Write-Host ("jobstate = " + $jobState)

if($jobState -ne "Failed"){
    Receive-Job $j -ErrorAction Stop
}

Remove-Job $j
output
jobstate = Failed

注意点としては、$ErrorActionPreference="Stop"にする必要があること、それと例外をキャッチしたらもう一度例外を投げる必要があることです。

$sb = {
    #ErrorActionPreferenceを設定
    #スクリプトブロックの外側の設定とはまた別なので注意!
    $ErrorActionPreference = "Stop"

    try {
        #存在しないコマンドを呼び出して例外発生
        hoge
    }
    catch {
        #ここで例外処理をする

        #例外をもう一度投げる
        throw
    }
}

$j = Start-Job $sb
Wait-Job -Job $j | Out-Null

$jobState = $j.State

Write-Host ("jobstate = " + $jobState)

if($jobState -ne "Failed"){
    Receive-Job $j -ErrorAction Stop
}

Remove-Job $j
output
jobstate = Failed

#参考
http://stackoverflow.com/questions/8751187/how-to-capture-the-exception-raised-in-the-scriptblock-of-start-job

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