Blog Archives

PowerShell: Catching terminating and non-terminating errors in PS Jobs (Job Pattern)


–update: the receive-job has had -ErrorAction Stop added to it. Thanks Witquicked

Recently someone asked how you’d catch non-terminating errors returned by a ps job and how to figure out what that error is. I thought this would be way easier than it was.

I also realized there wasnt much info out there on this so here is the code I came up with.

$jobs=@()
$jobs += Start-Job -ScriptBlock {write-error "--non term msg here"}
$jobs += Start-Job -ScriptBlock {throw "--term!"}
$jobs += start-job -ScriptBlock {"im successful"}
$jobs += start-job -ScriptBlock {while($true){}}
Wait-Job $jobs -Timeout 5

foreach($job in $jobs)
{
	write-host "--------"	
	write-host "Job ID: $($job.id)"	
	switch($job.state){	
		"Completed" {		
			write-host "job ran to completion"			
			if($job.ChildJobs[0].Error)			
			{			
				write-host "non terminating errors"				
				write-host $job.ChildJobs[0].Error			
			}		
		}	
		"Failed"	
		{		
			write-host "Job Terminated with error "			
			write-host "Error message is:"			
			try{Receive-Job $job -ErrorAction Stop }catch{$_.exception.message}		
		}	
		"Running"		
		{		
			write-host "Job is still running, Forcefully stopping it"			
			$job.StopJob()		
		}
	}
}

This is also a pattern for handling PS jobs in general.

You certainly dont want to loop, which I see people doing a lot. There is also a timeout param which I would highly suggest using.

Advertisements