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
This should be a comment really, but I don't have the reputation to leave comments.
My answer is that you should use Andy Arismendi's answer, but also output
$job.ChildJobs[0].Error
As
$job.ChildJobs[0].JobStateInfo.Reason.Message
isn't always useful.I was able to "rethrow" the exception in the main thread by using:
I'll my use case as an example. It can easily be applied to the OP.
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
Using
throw
will change the job object'sState
property to "Failed". The key is to use the job object returned fromStart-Job
orGet-Job
and check theState
property. You can then access the exception message from the job object itself.Per your request I updated the example to also include concurrency.