I have the following script,
$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
However, the exception raised in another powershell instance cannot be captured. What's the best way to capture the exception?
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
Beginning in PowerShell 6.0, you can use the background operator ( & ) at the end of a pipeline to start a background job. For more information, see background operator. Using the background operator is functionally equivalent to using the Start-Job cmdlet in the previous example.
To run a background job on a remote computer, use the AsJob parameter that is available on many cmdlets, or use the Invoke-Command cmdlet to run a Start-Job command on the remote computer.
You can use Stop-Job to stop background jobs, such as those that were started by using the Start-Job cmdlet or the AsJob parameter of any cmdlet. When you stop a background job, PowerShell completes all tasks that are pending in that job queue and then ends the job.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With