0

I am new to creating batch files in windows, I am trying to create a batch file to check the service in windows status, if the service is in running state then am trying to execute another command to check status but am not able to get the output for the second command.

Am checking the status of query by using %ERRORLEVEL%.

The following is my code in batch file :

@echo off
sc query "MpsSvc" | find "RUNNING"
echo "%ERRORLEVEL%"
if "%ERRORLEVEL%" EQU "0" (
     netsh advfirewall show currentprofile state | find "ON"
if "%ERRORLEVEL%" EQU "0" (
     echo firewall is already enabled
)
if "%ERRORLEVEL%" NEQ "0" (
     echo going to enable firewall
)
)
if "%ERRORLEVEL%" NEQ "0" (
     echo firewall service is not running
)
pause

When am trying to run my batch file am getting the %ERRORLEVEL% of the command echo firewall is already enabled only am getting for the another command echo firewall is already enabled.

Can anybody tell me what mistake I did?

3 Answers 3

2

Your proximate problem is, as noted in another answer, the early variable expansion in your nested if, but for errorlevel testing, do not use %ERRORLEVEL%, use

if not errorlevel 1 (...

the builtin syntax if errorlevel 5... tests wether the errorlevel is 5 or higher.
So not errorlevel 1 is true if the errorlevel is exactly 0.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to enable (and use) delayed expansion:

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables can be referenced using !variable_name!, in addition to the normal %variable_name%

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
sc query "MpsSvc" | find "RUNNING"
echo sc "%ERRORLEVEL%"
if "%ERRORLEVEL%" EQU "0" (
  netsh advfirewall show currentprofile state | find "ON"
  echo netsh "!ERRORLEVEL!"
  if "!ERRORLEVEL!" EQU "0" (
    echo firewall is already enabled
  ) else (
    echo going to enable firewall
  )
) else (
  echo firewall service is not running
)
pause

Resources (required reading):

Comments

0

Use goto

if somecondition goto label1
rem some script if somecondition FALSE
goto label2
:label1
rem some script if somecondition TRUE
:label2

Or call batch.bat (include all complex script in several batch file and use call to execute it and back to main batch file)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.