Windows Service : Setting Recovery Options & Sending Alert Email in case of service failure using PowerShell script

Recently, I was working on setting windows service recovery & alert options for getting notification in case of windows service failure. In this article, a simple approach for setting windows service recovery & alert options is explained.

Step 1: Open “Services.msc”, right click on the service for which you want to set recovery option, select “Properties” & go to Recovery tab.

Open Services

Services

Step 2: On “Recovery” Tab, setup recovery options in case of “First”, “Second” & “Subsequent” failures

In case of “First” & “Second” failure of windows service, “Restart the Service” option is set. Sometimes restart of the service automatically fixes the issue & no user action is required.

In case “Restart the Service” does not fixes the issue, i.e. in case of “Subsequent” failures,  “Run a Program” option is set to execute a PowerShell script (Alert.ps1). “Alert.ps1” PowerShell script contains the code for sending alert emails, in case of service failure, to user or group who are responsible for taking appropriate action based on the alert email.

Configuring Windows Service Recovery Options

Here:

Program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Command line parameters: -command C:\Users\Kapil\Desktop\Alert.ps1

Step 3: PowerShell Script for sending alert email

“Alert.ps1” PowerShell script contains the code for sending alert emails, in case of service failure, to user or group who are responsible for taking appropriate action based on the alert email.

Alert.ps1 file content

$EmailFrom = "alert@techcartnow.com"
$EmailTo = "kapil@techcartnow.com"
$Subject ="Alert:: Test service is down."
$Body = "Test service is down."
$SMTPServer = "smtp.office365.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("alert@techcartnow.com", "Password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Note: Replace “SMTP” details in the above PowerShell script with your “SMTP” details.

Alert Email

Email Alert

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *