.bat file: How setlocal enabledelayedexpansion came the rescue

Recently I was working on a script that verifies the service state for (RUNNING or PAUSED) and depending on the state, it should run some scripts. The problem was, I knew the state of my service and was testing my script and it was correctly passing the first if statement but failing to enter the if statement inside the else block. Turns out it was due to the lack of
setlocal enabledelayedexpansion
Adding that to my script fixed the problem.
@echo off
setlocal enabledelayedexpansion

rem This script uses "sc" and "net" to stop and delete the service

set "service_name=NGINX_SERVICE"

sc query "%service_name%" | findstr /C:"STATE" | findstr /C:"RUNNING"
echo "RUNNING (0=TRUE;OTHERWISE FALSE): !errorlevel!" 
if !errorlevel! equ 0 (
    echo Service is running. Stopping the service...
    net stop "%service_name%"
    sc stop "%service_name%"
    timeout /t 5 >nul
) else (
    REM Check if the service is paused (Without enabledelayedexpansion) this line would evaluate to 1 when 0 was actually the expected output. 
    sc query "%service_name%" | findstr /C:"STATE" | findstr /C:"PAUSED"
    echo "PAUSED (0=TRUE;OTHERWISE FALSE): !errorlevel!" 
    if !errorlevel! equ 0 (
        echo Service is paused. Stopping the service...
        net stop "%service_name%"
        sc stop "%service_name%"
        timeout /t 5 >nul
    ) else (
        echo Service is not running or paused.
    )
)

echo Deleting the service...
sc delete "%service_name%"

Leave a Reply

Close Menu