Bhuvanesh Waran
Bhuvanesh Waran

Reputation: 642

How to run multiple command in batch file with if condition

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?

Upvotes: 0

Views: 3662

Answers (3)

ths
ths

Reputation: 2942

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.

Upvotes: 2

JosefZ
JosefZ

Reputation: 30153

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):

Upvotes: 1

Y.N
Y.N

Reputation: 5257

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)

Upvotes: 0

Related Questions