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

前端 未结 4 560
说谎
说谎 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:43

    Using throw will change the job object's State property to "Failed". The key is to use the job object returned from Start-Job or Get-Job and check the State property. You can then access the exception message from the job object itself.

    Per your request I updated the example to also include concurrency.

    $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 
        }
    }
    

提交回复
热议问题