Check a Windows Service, if it's not running, start it via batch script

April 30, 2020

Following a system restart, an overnight shutdown or a system update, some Windows services don't always come up successfully. This script runs via Windows Task Scheduler and accepts one or more service names.

SC 3

Log files are produced when a service is found to not be running (updated 16/05)

If the service isn't running, it attempts to start it - and produces a log file to capture the incident.

The script is available on GitHub; the version at time of writing is here:

@Echo Off
:: ServiceCheck.bat
:: Accepts a service name, if it's running, exits. If it's not running, attempts to start it and creates a log file.
:: Uplift to check and retry?

Set ServiceName=%~1
::Set ServiceName=QlikSenseProxyService

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET LogDate=%%i

SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
  echo %ServiceName% not running 
  echo Start %ServiceName%
  Net start "%ServiceName%">nul||(
    Echo "%ServiceName%" wont start 
    exit /b 1
  echo "%ServiceName%" started
  :: Now log out to a file so we have some sort of history
  echo ### Service [%ServiceName%] not running on %LogDate% & echo %Time% Attempting to start service.>>"%~dp0ServiceCheck_%ServiceName%_%LogDate%.log"
  exit /b 0
  :: All OK, let's just write to console and exit
  echo "%ServiceName%" working
  exit /b 0

Configure the task (this example checks two Qlik Sense services) to accept one or more actions.

SC 1

Checked "Run whether user is logged on or not"

SC 2

Add one action per service

Profile picture

From Dave, who writes to learn things. Thoughts and views are his own.

© 2024, withdave.