Restarting Services with PowerShell

By | February 26, 2011

Thought I’d share a script I use to reset services nightly. This script will also e-mail if something goes wrong on the restart (which hasn’t ever been the case so far).

This specific reason I built this is for a Tomcat server that has some problems with errand threads (I didn’t build it and can’t change it). The only solution remaining to clean up these threads is a restart of the Tomcat process.

The nice part about PowerShell versus something like a batch file is that with little scripting the PowerShell script will “wait” for the services to change.

Here is the code, substitute your settings where applicable. Feel free to modify as needed. It goes without saying that you should test this on a non-production server before using.

[ps]
## Reference to System.Net for email alerts
[void][System.Reflection.Assembly]::LoadWithPartialName(“System.Net.Mail”)

function restart-service
{
param ($srvName)

## stop service
stop-Service $srvName
$service = get-service $srvName

if($service.status -ne “Stopped”)
{
email-admin($srvName + ” has failed to stop, please manually stop and restart.”)
write($srvName + ” has failed to stop, please manually start.”)
}

##start service
start-Service $srvname
$service = get-service $srvName
if($service.status -ne “Running”)
{
email-admin($srvName + ” has failed to start, please manually start.”)
write($srvName + ” has failed to start, please manually start.”)
}
else
{
write($srvName + ” has started.”)
}
}

##email if failed
function email-admin($body)
{
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = “psScript@server”
$mail.To.Add(“your@email.com”)
$mail.Subject = “Service Restart”
$mail.Body = $body
$smtp = New-Object System.Net.Mail.SmtpClient(“your.smtp.com”)
$smtp.Send($mail)
}

restart-service BITS
[/ps]

I save this file as restartService.ps1 in my c:\PSScripts folder.

In order to add this as a regular scheduled task I use the following command:

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -nolog -command “&{c:\PSScripts\restartService.ps1}”

Happy restarting!

Share and Enjoy