Powershell Script to Email Me when a Service Stops

On our current DAG On Premises Environment I was experiencing issues when our Cluster Service kept stopping and it wouldn’t restart L I wanted to know the reasoning behind this, but it was so random at times, I couldn’t just sit there and wait for it to happen (who has time for that anyway?)

I created a simple Powershell Script to email me when the service Stops and get it restarted again.

Below is the Script – you’ll need to change the parts to fit into your environment.

$ComputerName = (get-wmiobject Win32_Computersystem).name
$ServiceName = $args[0]
$ServiceDisplayName = (Get-Service $ServiceName).DisplayName
$TimesRestarted = $args[1]

Get-Service $ServiceName
$Status = (Get-Service $ServiceName).Status
If ($Status -ne "Running")
Start-Service $ServiceName

function SendAlert
$FromAddress = "ServiceFailure@SCCMNoob.com"
$ToAddress = "Craig@SCCMNoob.com"
$MessageSubject = "Cluster Service Failure for $ComputerName"
$MessageBody = "The $ServiceDisplayName ($ServiceName) service on $ComputerName has restarted $TimesRestarted times in the last 24 hours, please investigate immediately"
$SendingServer = "smtp.SCCMNoob.co.uk"

###Create the mail message and add the statistics text file as an attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody

###Send the message
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer


Copy the script, save it in .PS1 then copy it into a generic location (Normally I have a folder on C:\Scripts)

 Then head over to your Server, open Services.msc on the server

Select your services (in this example I’m using it on the Clustering service – it can be used on any running service)


The first failure I get it to restart the service….if it has any issues it will then “Run a Program” which will execute my Powershell script

Command line parameters:
-command “& {C:\Scripts\ServiceStopsSendEmail.ps1 ‘ClusSvc’ %1%}”

‘ClusSvc’ is the Service name of the Service, this can be found on the “General Tab”

If this has worked, you should receive and email like below 🙂




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