Verify a service is running with Powershell

24 Aug 2012

We use Spiceworks to manage our helpdesk and IT infrastructure. Frequently we would find that the ‘spiceworks’ service would be stopped for one reason or another on the server, which prevented our users from entering helpdesk tickets (bad!).

At this point in time we did not want to implement something like Nagios to ensure everything is up and running so I wrote a small Powershell script that will check the status of a service and if it’s not running send an email and attempt to restart the service. This gives IT a heads up there may be an issue with the server, and hopefully proactively get’s things running again without any intervention on our part.

We have this called via Windows Scheduler every 15 minutes. For execution, run the script and pass the service name like so: verify_service_status.ps1 [Service]

###################################################################
# verify_service_status.ps1
# Created: 09/14/2012
# Author: Me
# Summary: Verify a service is running, send email if it's down
###################################################################
#####################################
# Send Email Function
#####################################
 function sendMail($service, $serverNM){
 
     #SMTP server name
     $smtpServer = "XXX.XXX.XXX.XXX"
	 
     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
     $msg.From = "Server@example.com"
     $msg.ReplyTo = "ImportantPeople@example.com"
     $msg.To.Add("ImportantPeople@example.com"
	 $msg.To.Add("ImportantPeople@example.com"
     $msg.subject = 'Alert ' + $Service + ' is not running on ' + $serverNM
     $msg.body = "The following service is not running on " + $serverNM + " and has attempted to be restarted: " + $Service

     #Sending email
     $smtp.Send($msg)
 
}

##############################
# Get service status
##############################
if($args[0] -ne $NULL){

	$serviceName = $args[0]
	$serverName = hostname

	$status = (Get-Service $serviceName).Status

	if ($status -ne "Running"){
		sendMail "$serviceName" "$serverName"
		Restart-Service $ServiceName
	}else{
			# Service is running, do nothing;
	}
}