Page 1 of 1

Strange %ERRORLEVEL% Behavior [SOLVED]

Posted: 20 Aug 2021 11:37
by atfon
I'm sure it is something wrong with my script :? but, I am seeing some strange behavior with checking the %ERRORLEVEL% when I attempt to check the firewall status using the netsh command:

Code: Select all

@echo off
setlocal enabledelayedexpansion
netsh advfirewall show currentprofile |findstr /i "State" |findstr /i "ON" >nul
if "%ERRORLEVEL%"=="0" (
set "fRules=ON"
) else (
set "fRules=OFF"
)
echo %fRules%
pause > nul
All I see on the console is:

pause 1>nul

If I remove the quotes in front of fRules, I get the following:

ON"

I have also tried IF %ERRORLEVEL% EQU 0 and the negation with IF %ERRORLEVEL% NEQ 0 to no avail. I would appreciate any advice.

Re: Strange %ERRORLEVEL% Behavior

Posted: 20 Aug 2021 12:40
by aGerman
If %fRules% is expanded the resulting command is either echo ON or echo OFF. Does this look somehow familiar? :D In fact, these are the commands to turn the prompt on and off. You use it all the time in the first line of a batch code. You can get around this by using the (somewhat weird) syntax
echo(%fRules%
intentionally without space and without closing parenthesis.

Steffen

Re: Strange %ERRORLEVEL% Behavior

Posted: 20 Aug 2021 12:46
by atfon
HI Steffen. Thanks again. Funny how things seem obvious in hindsight. I was wondering why it seemed to turn the prompt on! :oops:

Your method works just fine, but I just changed the verbiage to set "fRules=Enabled" and "fRules=Disabled" instead.

Re: Strange %ERRORLEVEL% Behavior [SOLVED]

Posted: 20 Aug 2021 13:05
by Squashman
You can use a single FINDSTR command.

Code: Select all

findstr /RC:"^State *ON$"

Re: Strange %ERRORLEVEL% Behavior [SOLVED]

Posted: 20 Aug 2021 13:38
by atfon
Thanks, Squashman. That's a good point. As there are usually multiple ways to accomplish a task, this also works:

Code: Select all

findstr "\<State.*ON\>"