How to capture the exception raised in the scriptblock of start-job?

前端 未结 4 558
说谎
说谎 2020-12-29 23:08

I have the following script,

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


        
4条回答
  •  我在风中等你
    2020-12-29 23:40

    I was able to "rethrow" the exception in the main thread by using:

    Receive-Job $job -ErrorAction Stop
    

    I'll my use case as an example. It can easily be applied to the 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
    

    Works in v2.0.

    Note that if the error within the job is non-terminating, the subsequent lines will continue to execute. But, this will not be obvious in the output returned from Receive-Job, as Receive-Job "terminates half way thorugh" - it throws out of it's self when the error object is encountered.

    One way to avoid that is to wrap the whole block in a try {} catch{throw;}

    Also, Job state will not be 'Failed' if the exception is non-terminating

提交回复
热议问题