First off, I don't understand your syntax. I'm running PS v5 on Windows 10 and your code snippet doesn't even run, because you fed Start-Job
a string, not a script block. And -sb
was not an acceptable alias/shorthand for -ScriptBlock
for me.
But who knows, maybe that was legal in PS v4. That's beside the point.
You should add -ErrorAction Stop
to your dir
/gci
/get-childitem
cmdlet so that it produces a "terminating" error if it fails.
Behold, here is the job when I do not specify -ErrorAction Stop
:
PS C:\> $MyJob = Start-Job -ScriptBlock { (Measure-Command{Dir \\$DCName\sysvol\$Domain\Policies}).Milliseconds }
PS C:\> $MyJob.State
Running
PS C:\> $MyJob.State
Completed
I won't know whether the job actually succeeded or failed. The state of the job simply goes from Running to Completed, regardless of the job's success.
Now let's try it again with a terminating error:
PS C:\> $MyJob = Start-Job -ScriptBlock { (Measure-Command{Dir \\$DCName\sysvol\$Domain\Policies -ErrorAction Stop}).Milliseconds }
PS C:\> $MyJob.State
Running
PS C:\> $MyJob.State
Failed
Now you see that the same job enters a state of Failed. You now know your job failed. In addition, if you were to save the results of the job with
PS C:\> $Result = Receive-Job $MyJob
$Result
will be null if the job failed.
If you want to store the specific error that occurred within the job, try this:
PS C:\> Receive-Job $MyJob -ErrorVariable Result
PS C:\> $Result
Cannot find path '\\\sysvol\\Policies' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\\sysvol\\Policies:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost