This script was originally created to run as a scheduled task. All variables will have to be updated to fit with your own environment i.e. $hostname, $smtpserver. Once run it will complete the following –
1. Send an e-mail to whichever address/s that you specify within the $recipients variable. In my case this was used to inform the alert monitoring team that they can ignore alerts for this service over the next 10 mins.
2. Stop the service specified within the $service variable. A do..Until loop was used to confirm the service had stopped before continuing with the script.
3. Start the service. Again, a do..Until loop was used to confirm the service had started.
4. Send an e-mail to the same recipients informing them that the service has restarted successfully.
# Author: Simon Rowe # Created: 6th Feb 2014 # Description: 1. Sends an e-mail informing relevant parties that the service is about to restart. # 2. Stops the service and confirms the status as stopped. # 3. Starts the service and confirms the status as Running. # 4. Sends an e-mail informing support that the service has restarted successfully. # Send e-mail to alert users of Apache service restart $hostname = hostname $smtpServer = 'mail.domain.local' $from = "Service.$hostname@domain.com" $recipients = 'support@domain.com','operations@domain.com' $Subject = "Restarting msiserver Service on $hostname" $body = "This is an automated message to confirm that the msiserver service on $hostname is about to be restarted as part of scheduled maintenance, please ignore any alerts for the next 10 minutes from this service." Send-MailMessage -To $recipients -Subject $Subject -Body $body -From $from -SmtpServer $smtpServer # Stop service $service = 'msiserver' Stop-Service -name $service -Verbose do { Start-sleep -s 5 } until ((get-service $service).Status -eq 'Stopped') # Start service start-Service -name $service -Verbose do { Start-sleep -s 5 } until ((get-service $service).Status -eq 'Running') # Send confirmation that service has restarted successfully $Subject = "msiserver Service Restarted Successfully on $hostname" $body = "This mail confirms that the msiserver service on $hostname is now running. Operations, please restart your IXP GUI on your monitoring workstations to confirm they are showing correct information" Start-Sleep -s 5 Send-MailMessage -To $recipients -Subject $Subject -Body $body -From $from -SmtpServer $smtpServer
Hello Simon,
Wonder if you can help me.
I am trying to get a powershell script together that runs on a scheduled task of 5-10 min intervals. I want the script to send an email when a named service stops on a server of my choice. Every script I have created sends an email regardless of if the service is stopped or not.
Are you able to give me any advice or at least something that will give me food for thought?
Kind regards,
Joe