Yes we have SCOM monitoring and stuff, but if some testing or debugging is going on and do don’t want to do down the hassle of setting up alerts and just simply want to get notified when a service goes down, here is a simple script
1 2 3 4 5 6 7 8 |
$status = (Get-Service "<ServiceName>").Status while ($status -eq "Running") { Start-Sleep -Seconds 10 } Send-MailMessage -From "<FromAddress>" -To "<ToAddress>" -Body "<Body>" -Subject "<Subject>" -SmtpServer "<SMTPServer>" |
It’s pretty self explanatory.
You can also send it to multiple recipients
1 2 3 4 5 6 7 8 9 10 |
$status = (Get-Service "<ServiceName>").Status while ($status -eq "Running") { Start-Sleep -Seconds 10 } $recipients = @("<Recipient1>","<Recipient2>") Send-MailMessage -From "<FromAddress>" -To $recipients -Body "<Body>" -Subject "<Subject>" -SmtpServer "<SMTPServer>" |
Voila!! It will check every 10 seconds and if the service is in any other state apart from “Running”, it will send you an email and stop execution.
Update: And easy to bring it back up when it goes down. Run the following in PS as Admin. It will send a mail when service is down and bring it back up.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Function FixService() { Send-MailMessage -From <FROMADDRESS> -To <TOADDRESS> -Body "<ServiceName> at $($(Get-Date).ToLongTimeString())" -Subject "<SUBJECT>" -SmtpServer <SMTPSERVER> Start-Service "<ServiceName>" Write-Host "Service restarted at $($(Get-Date).ToLongTimeString())" -ForegroundColor Cyan CheckService } Function CheckService() { Write-Host "Service is running" -ForegroundColor Green while ((Get-Service "<ServiceName>").Status -eq "Running") { Start-Sleep -Seconds 10 } Write-Host "Service stopped at $($(Get-Date).ToLongTimeString())" -ForegroundColor Red FixService } CheckService |
1 Comment
Ramesh · 10/03/2024 at 4:28 AM
Hi Piyush
How do you pass smtp credentials to this? i use sendgrid and want to how to pass username & password