Errorlevel oddities

Microsoft Windows
Post Reply
Syntax
Posts: 3
Joined: 2023-Oct-05, 9:37 pm

Errorlevel oddities

Post by Syntax »

I have a bit of code that I'm using to check if a service exists.

Code: Select all

:: Check if the MyService service exists
where sc >nul 2>nul
if %errorlevel% equ 0 (
    sc query MyService | find "STATE" >nul
    echo Errorlevel is %errorlevel%
    if %errorlevel% neq 0 (
	echo MyService service does not exist.
        goto RIGHT
    )
) else (
    echo "The script was unable to locate sc.exe .  The installer script uses sc.exe to check if the MyServcie service is installed and in a RUNNING state.  To remedy this error, copy sc.exe from a Windows PC that is the same version as this PC and place it in %windir%\System32.
    pause
    exit /b
)

:WRONG
echo This is the wrong area
exit /b

:RIGHT
echo This is the right area
exit /b
On my test box, MyService does not exist and I'm expecting errorlevel to be 1. However, when I run this, errorlevel is 0 and it's leading me to :WRONG.

If I manually run this, errorlevel is 1

Code: Select all

sc query MyService   | find "STATE"  1>nul
User avatar
Simon Sheppard
Posts: 189
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: Errorlevel oddities

Post by Simon Sheppard »

I think you are being bitten by delayed expansion

Change the start to something like this to get the main part outside of the brackets

Code: Select all

:: Check if the MyService service exists
where sc >nul 2>nul
if %errorlevel% neq 0 goto SC_MISSING

sc query MyService | find "STATE" >nul
echo Errorlevel is %errorlevel%
...
Syntax
Posts: 3
Joined: 2023-Oct-05, 9:37 pm

Re: Errorlevel oddities

Post by Syntax »

Works like a charm. Nice and concise. Thanks, Mr. Simon!
Post Reply