如何捕获start-job的scriptblock中引发的异常?

ca9*_*3d9 22 powershell powershell-2.0

我有以下脚本,

$createZip = {
    Param ([String]$source, [String]$zipfile)
    Process { 
        echo "zip: $source`n     --> $zipfile"
        throw "test"
    }
}

try {
    Start-Job -ScriptBlock $createZip -ArgumentList "abd", "acd"  
    echo "**Don't reach here if error**"
    LogThezippedFile
}
catch {
    echo "Captured: "
    $_ | fl * -force
}
Get-Job | Wait-Job 
Get-Job | receive-job 
Get-Job | Remove-Job 
Run Code Online (Sandbox Code Playgroud)

但是,无法捕获在另一个PowerShell实例中引发的异常.捕获异常的最佳方法是什么?

Id              Name            State      HasMoreData     Location             Command                  
--              ----            -----      -----------     --------             -------                  
343             Job343          Running    True            localhost            ...                      
**Don't reach here if error**
343             Job343          Failed     True            localhost            ...                      
zip: abd
     --> acd
Receive-Job : test
At line:18 char:22
+ Get-Job | receive-job <<<<  
    + CategoryInfo          : OperationStopped: (test:String) [Receive-Job], RuntimeException
    + FullyQualifiedErrorId : test
Run Code Online (Sandbox Code Playgroud)

And*_*ndi 26

使用throw会将作业对象的State属性更改为"失败".关键是使用从Start-Job或返回的作业对象Get-Job并检查State属性.然后,您可以从作业对象本身访问异常消息.

根据您的请求,我更新了示例以包含并发性.

$createZip = {
    Param ( [String] $source, [String] $zipfile )

    if ($source -eq "b") {
        throw "Failed to create $zipfile"
    } else {
        return "Successfully created $zipfile"
    }
}

$jobs = @()
$sources = "a", "b", "c"

foreach ($source in $sources) {
    $jobs += Start-Job -ScriptBlock $createZip -ArgumentList $source, "${source}.zip"
}

Wait-Job -Job $jobs | Out-Null

foreach ($job in $jobs) {
    if ($job.State -eq 'Failed') {
        Write-Host ($job.ChildJobs[0].JobStateInfo.Reason.Message) -ForegroundColor Red
    } else {
        Write-Host (Receive-Job $job) -ForegroundColor Green 
    }
}
Run Code Online (Sandbox Code Playgroud)


wax*_*cal 8

这应该是一个评论,但我没有留下评论的声誉.

我的答案是你应该使用Andy Arismendi的答案,但也要输出 $job.ChildJobs[0].Error

因为$job.ChildJobs[0].JobStateInfo.Reason.Message并不总是有用.

  • `$job.ChildJobs[0].Error` 返回所有非终止错误。`$job.ChildJobs[0].JobStateInfo.State` 返回终止错误(如果有)(State == Failed)。[来源](https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/13399002-powershell-jobs-error-handling) (2认同)

Pat*_*ick 5

我能够使用以下方法在主线程中“重新抛出”异常:

Receive-Job $job -ErrorAction Stop
Run Code Online (Sandbox Code Playgroud)

我将以我的用例为例。它可以很容易地应用于 OP。

$code = {
    $Searcher = New-Object -ComObject Microsoft.Update.Searcher
    #Errors from Search are not terminating, but will be present in the output none the less.
    $Results = $Searcher.Search('IsInstalled=0  and IsHidden=0')
    $Results.Updates
};
$job = Start-Job -ScriptBlock $code;
$consume = Wait-Job $job -Timeout 600;

if ($job.state -eq 'Running') {
    Stop-Job $job
    throw 'Windows update searcher took more than 10 minutes. Aborting' 
};

#Captures and throws any exception in the job output
Receive-Job $job -ErrorAction Stop;
Write-Host "Finished with no errors"; #this will not print if there was an error
Run Code Online (Sandbox Code Playgroud)

在 v2.0 中工作。

请注意,如果作业中的错误是非终止的,则后续行将继续执行。但是,这在从 Receive-Job 返回的输出中并不明显,因为 Receive-Job “中途终止” - 当遇到错误对象时,它会自行抛出。

避免这种情况的一种方法是将整个块包装在 try {} catch{throw;}

此外,如果异常是非终止的,作业状态不会是“失败”