Monitor event logs and restart service by Powershell script
2024年10月15日
Table of Contents
ToggleSettings
- Run the task every 15 minutes on task scheduler.
- Get the event ID within 15 minutes in the Powershell script.
- If it sees a Warning log, restart the specified service.
- Send an email just in case.
Powershell script
Update From/To address, SERVICE_NAME, and EVENT_ID according to your preference and create a .ps1 file. If you don't have an SMTP server in your environment, you can delete the part to send an email.
# Settings
$From = "from@example.com"
$time = Get-Date -DisplayHint Time
$To = "to@example.com"
$SMTPServer = "192.168.X.X"
$Port = "25"
$Service = "SERVICE_NAME"
$EventId = "EVENT_ID"
# Check Event log ID within 15 mins
$EventLogs = Get-EventLog -LogName Application -InstanceId $EventId -EntryType Warning -after (Get-Date).AddMinutes(-15) | FT TimeGenerated, InstanceID, Message -AutoSize
# Restart the service and send an email
If ($null -ne $EventLogs) {
Restart-Service -Name $Service
# Send an email
$Subject="Service " + $Service + " restarted at " + $time
$body = "Event Log ID " + $EventId + " with Warning detected. Restarted the service."
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer,$Port)
$SMTPClient.EnableSsl=$false
$MailMassage = New-Object Net.Mail.MailMessage($From,$To,$Subject,$body)
$SMTPClient.Send($MailMassage)
}
# Check the service state
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
Add a Task Scheduler task
Trigger
Repeat task every 15 minutes. Update it as you like.
Action
Choose "Start a program".
- Program/script
C:WindowsSystem32WindowsPowerShellv1.0powershell.exe
- Add arguments
Specify the .ps1 file you created.
-ExecutionPolicy Bypass -File "C:ScriptsMonitorEventLogs.ps1"
I hope this information will be helpful to you.
You May Also Like

Set up Yubikey PIV Authentication for Windows RPD Sessions
2024年9月20日