Blog Archives

Using PowerShell Schedule Job to Reboot a Computer


I have to reboot a server tonight and well, I don’t want to have to VPN in to do it tonight. I know there is a Restart-Computer cmdlet which is cool but i need to schedule it, so i decided to use the PS Scehduled Job and came up with this


register-ScheduledJob -Name systemReboot -ScriptBlock {

Restart-Computer -ComputerName $server -Force -wait

Send-MailMessage -From jrich523@domain.com -To jrich523@domain.com -Subject "Rebooted" -SmtpServer smtp.domain.com

} -Trigger (New-JobTrigger -At "11/28/2012 6:00pm" -Once) -ScheduledJobOption (New-ScheduledJobOption -RunElevated) -Credential (Get-Credential)

Sorry, it’s one long line, but copy and paste it and you’ll be happy you took the time to figure it out.

Two important notes here are that I used the New-ScheduledJobOption to force it to run elevated, which is more often than not, needed.

The other part, which sort of threw me for a loop was that you have to specify credentials even if they are the creds you are currently logged in as. The reason for this is that if you don’t you wont have the creds in the job pass through to the script.

 

 

 

Enjoy!

Advertisements

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.