Article ID: kb00124Last Modified: 22-Aug-2024

Scheduled Monitoring Of Windows Service Status

In some case it is required to monitor the status of a Windows service and automatically restart it.

The following PowerShell snippet creates a task in the Task Scheduler that checks the status of a service at regular intervals and attempts to start it in case it's not running.

# Omit the next line if running interactively
if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -WindowStyle Hidden -Command `"& {`$Servicename = 'name-of-the-service'; `$service=Get-service -Name `$Servicename; if (`$service.Status -eq 'Stopped') {Start-Service -Name `$Servicename}}`""
# Creating base trigger:
$trigger = New-ScheduledTaskTrigger -At 00:00:01 -Daily
# Creating secondary trigger:
$trigger2 = New-ScheduledTaskTrigger -At 00:00:01 -Once -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 59)
# Taking repetition object from secondary, and insert it into base trigger:
$trigger.Repetition = $trigger2.Repetition
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Restart of Backup Service" -User "System"

# Omit the next line if running interactively
Read-Host -Prompt "Press Enter to exit"

Take the following steps:

  1. Replace the name-of-the-service string with the Display name of the monitored Windows service as shown in its properties (accessible in services.msc via right-click context menu);

  1. Execute the PowerShell code:

Option A: Open a PowerShell prompt under the administrator account. Copy and execute the script except for the lines that follow the #Omit the next line if running interactively comments;

Option B: Save the script as a PS1 file and run it via the right-click context menu > Run with PowerShell. UAC prompt will appear to confirm administrative privileges;

  1. Make sure that the created task does what's expected of it: Go to services.msc again and stop the monitored service. The service should start at the next 5-minute mark.

Contact Us

https://git.cloudberrylab.com/egor.m/doc-help-kb.git