Skip to content

Instantly share code, notes, and snippets.

@VertigoRay
Last active December 14, 2015 12:29
Show Gist options
  • Save VertigoRay/5086677 to your computer and use it in GitHub Desktop.
Save VertigoRay/5086677 to your computer and use it in GitHub Desktop.
Used with Win Service Recovery to recover servers that Exit Unclean. Will log to file and retry n times. Implementation Screenshots: http://imgur.com/a/dmqq8
@echo off
setlocal
SET /A RETRYMAX=10
SET LOG=%SystemRoot%\Logs\ServiceRecovery.log
FOR /F "tokens=2*" %%a in ('sc query %1 ^| findstr STATE') do SET STATUS=%%b
SET STATUS=%STATUS: =%
IF ERRORLEVEL 1 goto _errawr
IF "%STATUS%"=="4RUNNING" goto:eof
echo [%date% %time%] (%1) Warning: %2 Detected as Down (%3 %4). >> %LOG%
SET /A RETRY=1
:loop
echo [%date% %time%] (%1) Restarting %2 (Attempt:%RETRY%) ... >> %LOG%
sc start %1
:_pending
ping -n 1 -w 1000 127.0.0.1
FOR /F "tokens=2*" %%a in ('sc query %1 ^| findstr STATE') do SET STATUS=%%b
SET STATUS=%STATUS: =%
IF ERRORLEVEL 1 goto _errawr
echo [%date% %time%] (%1) Status: %STATUS% >> %LOG%
IF "%STATUS%"=="2START_PENDING" goto _pending
IF "%STATUS%"=="4RUNNING" goto _running
IF "%RETRY%"=="%RETRYMAX%" goto _retrymaxed
SET /A RETRY+=1
goto loop
:_running
echo [%date% %time%] (%1) Success: %2 is Running! >> %LOG%
goto:eof
:_retrymaxed
echo [%date% %time%] (%1) Error: Retry Limit (%RETRYMAX%) Exceeded >> %LOG%
goto:eof
:_errawr
echo [%date% %time%] (%1) Error: Critical Error >> %LOG%
goto:eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment