Created
August 29, 2018 19:58
-
-
Save PFortin93/2cf373c9fbfd3353291285e5762fb81a to your computer and use it in GitHub Desktop.
Checks if a log file has been written to in the last 30 minutes, Restarts a Windows Service if it has not been
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Checks if JobAlerts has written a log in the last 30 minutes. Restarts it if it has not. | |
| #Should it do stuff, It sends an email | |
| #Pierce Fortin [email protected] | |
| #Logic test on a working service: Change -lt on 28 to -gt | |
| #ScriptSettings | |
| $WaitPeriod = '20' #Wait time in seconds before starting a service if it is in a failed state | |
| $LogPath = 'C:\scripts\jobalerter\runlog.log' | |
| $serviceName = 'ServiceName' | |
| $lastModifiedDate = (Get-Item "C:\Stuff\MoreStuff\logs\Service_Log.txt").LastWriteTime | |
| #Email Settings | |
| $emailfrom = '[email protected]' | |
| $emailto = '[email protected]' | |
| $emailSubject = "Service Stalled: Restarted Service on $env:computername" | |
| $smtpserver='mailprod.domain.com' | |
| #Transcript Settings: | |
| $ErrorActionPreference="SilentlyContinue" | |
| Stop-Transcript | out-null | |
| $ErrorActionPreference = "Continue" | |
| Start-Transcript -path $logpath | |
| #Check if file has been modified in last 30 minutes, If it has not restart service and trigger email | |
| if ($lastModifiedDate -lt (Get-Date).AddMinutes(-30) ) { | |
| write-host "file not modified in last 30 minutes" | |
| Stop-Service -name $serviceName | |
| Start-Sleep -Seconds $WaitPeriod | |
| Start-Service -name $serviceName | |
| #Send email with the status | |
| write-host "Service was restarted" | |
| Stop-Transcript | |
| $body = @" | |
| Service Stalled automated recovery performed on $env:computername. | |
| Last modified date on Logfile is $lastModifiedDate | |
| See attached logfile for details. | |
| "@ | |
| $message = new-object System.Net.Mail.MailMessage | |
| $message.From = $emailfrom | |
| $message.To.Add($emailto) | |
| $message.IsBodyHtml = $True | |
| $message.Subject = $emailSubject | |
| $attach = new-object Net.Mail.Attachment($logpath) | |
| $message.Attachments.Add($attach) | |
| $message.body = $body | |
| $smtp = new-object Net.Mail.SmtpClient($smtpserver) | |
| $smtp.Send($message) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment