Check if a Windows Service is running and restart if not

Created by: Gunnar Steinn Magnússon

In this article, you will learn how to check if a Windows Service is running and restart if not, in exMon DG. Many applications use Windows Services for background jobs and in some cases, they might be unstable. For example, an unstable point of sales (POS) service could stop all transactions while down, and requires manual interventions by IT people.

With exMon, you can automatically monitor and restart these services, reducing the manual work of remoting and restarting. In addition, exMon will keep a log of all instances helping IT to pinpoint and audit these failures.

Create a control in exMon DG

  1. Create a Query with a PowerShell data provider
  2. Add the following code
    $serviceName = '{@servicename[preview:exMon Command Service]}'
    $service = Get-Service -Name $serviceName | select Displayname,Status,@{label="NewStatus";expression={$_.Status}},@{label="Hostname";expression={[System.Net.Dns]::GetHostName()}}
    if ($service.Status -ne 'Running') {
      # The service is stopped. Restart and fetch new status
      Start-Service $serviceName
      $service.NewStatus = (Get-Service -Name $serviceName | select Status).Status
    } else {
      $exMonResult= New-Object system.Data.DataTable
      $col1 = New-Object system.Data.DataColumn DisplayName,([string])
      $col2 = New-Object system.Data.DataColumn Status,([string])
      $col3 = New-Object system.Data.DataColumn NewStatus,([string])
      $col4 = New-Object system.Data.DataColumn Hostname,([string])
      #return empty results when everything is OK
  3. Run the query and configure the control as normally.
  4. Note that you can select a specific machine to run the query on by creating a specific PowerShell data provider, connected to a specific Execution Connection.
  5. Deploy the control

You can then list each service by adding it to a Schedule Group, Object Group, or Process by adding parameters as shown below:


Here is an example of output for the control

Gunnar is the author of this solution article.