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

About jrich

I am the Solutions Architect for Apex Learning in Seattle WA. I've been working with computers since I was 13. Started programming when I was 14. Had my first IT job as tech support at an ISP at the age of 15 and became a network admin at the age of 17. Since then I've worked at a variety of small to mid size companies supporting, maintaining and developing all aspects of IT. Mostly working with Windows based networks but have recently been working with Solaris system as well. I created this blog mostly as a place for me to take my own notes, but also share things that I had a hard time finding the info for.

Posted on August 8, 2012, in WMF (Powershell/WinRM) and tagged , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: