My Technical Notes

Thursday, 17 December 2015

PowerShell: Checking if a job has failed

When using `Start-Job` to run a script block, we need to check the job for errors once it finishes.

We first use the job's `State` property to see if `Completed` or `Failed`. In some instance, it may have `Completed` state, but it still failed in some way.


$job.State

Next, we can check the `ChildJobs[0].Error`:


$job.ChildJobs[0].Error

If we threw (an exception or string etc) during the execution then we can check:


$job.ChildJobs[0].JobStateInfo.Reason.Message

The above is essential if we place:


$ErrorActionPreference = 'Stop'

At the top of the script block.

No comments: