Tuesday, June 28, 2016

Restart Windows Service on failure and send mail - PowerShell


How to send email if a windows service stops?



In order to run a PowerShell script you first must define the program in this case you provide the full path to the PowerShell EXE.

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

The next you add in the remaining commands you want to execute when running the program. What I did was the following.

-command “& {C:\Skripte\ServiceAlertFromRecovery.ps1 ‘MSCRMAsyncService’ %1%}”


 Inside the script there are a few variables you will want to change. The items to change are all located near the top and are located in the “SendAlert” function.
  • $FromAddress = The from address for the email.
  • $ToAddress = You can use one or more email addresses separated by commas and all contained within the quotes.
  • $MessageSubject = This can be changed based on your needs but most likely doesn’t need any changing.
  • $MessageBody = This can be changed based on your needs but most likely doesn’t need any changing.
  • $SendingServer = The IP Address of the SMTP server you want to use.

$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@domain.com"
  $ToAddress = "emailaddr@domain.com"
  $MessageSubject = "Service Failure for $ComputerName"
  $MessageBody = "The $ServiceDisplayName ($ServiceName) service on $ComputerName has restarted $TimesRestarted times in the last 24 hours. Please review server event logs for further information."
  $SendingServer = ""

  ###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
  $SMTPClient.Send($SMTPMessage)
}

SendAlert 
 
 
Download script 


Ref: http://it-erate.com/restart-windows-service-failure-powershell-script/





No comments:

Post a Comment