Batch file ErrorLevel woes
I am wr开发者_StackOverflow社区iting a batch file to upgrade some systems. I need to parse a date from an xml file and save it for use later in the file. The format of the date is yyyy\MM\dd.
What I have so far is:
@echo off
setLocal DisableDelayedExpansion
for /f "tokens=* delims= " %%G in (ConnectionManagement.xml) do (
set str=%%G
set mydate=%%G
echo got-
echo %%G
echo %mydate%
PAUSE
ECHO %mydate%|findstr /R /C:[0-9][0-9][0-9][0-9]\\[0-9][0-9]\\[0-9][0-9] > nul
IF ERRORLEVEL 0 goto valueok
)
echo DONE
PAUSE
goto end
:valueok
echo VALUEOK
:end
PAUSE
Unfortunately this incorrectly recognised the xml header as a valid date; but I think this is to do with ErrorLevel being reset (?). mydate isn't being set, and it recognises the empty variable mydate as a match (!!??). The output is:
got-
<?xml version="1.0" encoding="utf-8"?>
ECHO is off.
Press any key to continue . . .
VALUEOK
Press any key to continue . . .
...
Getting rather desperate for a solution. thanks...
ErrorLevel is not being reset. What is actually happening is that IF ERRORLEVEL 0
does not behave the way you expect. Basically, the test is not "Does errorlevel equal 0?", its "Is errorlevel greater than or equal to zero?". Given this, it should be clear that IF ERRORLEVEL 0
will always be true (at least, if you only expect positive errors...)
Therefore, you need to use IF NOT ERRORLEVEL 1 goto valueok
instead.
As RB wrote, IF ERRORLEVEL 0
does not behave the way you expect.
The if errorlevel
is a special IF-case.
To use a normal IF-construct you could use
setlocal EnableDelayedExpansion
...
FOR-LOOP .. DO (
if !ERRORLEVEL! EQU 0 goto valueok
精彩评论