Reputation: 642
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
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
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):
IF
command) Conditionally perform a commandUpvotes: 1