Strange %ERRORLEVEL% Behavior [SOLVED]

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Strange %ERRORLEVEL% Behavior [SOLVED]

#1 Post by atfon » 20 Aug 2021 11:37

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.
Last edited by atfon on 20 Aug 2021 12:49, edited 1 time in total.

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Strange %ERRORLEVEL% Behavior

#2 Post by aGerman » 20 Aug 2021 12:40

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

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: Strange %ERRORLEVEL% Behavior

#3 Post by atfon » 20 Aug 2021 12:46

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.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Strange %ERRORLEVEL% Behavior [SOLVED]

#4 Post by Squashman » 20 Aug 2021 13:05

You can use a single FINDSTR command.

Code: Select all

findstr /RC:"^State *ON$"

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: Strange %ERRORLEVEL% Behavior [SOLVED]

#5 Post by atfon » 20 Aug 2021 13:38

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\>" 

Post Reply