Batch programming setting ERRORLEVEL from failed FIND command
-
13-07-2021 - |
Frage
I have found the need to report an error level to a program that calls batch scripts.
The script will create a CSV log file that I would like to check in order to display whether the script was run successfully.
What I would like to say is something like
IF NOT FIND "[ERR" "test.csv"
or to say, that if the string "[ERR"
is not in the output ERRORLEVEL = 0 ELSE ERRORLEVEL = 1
Hope this makes sense. I'm sure it is simple but setting error levels seems to be a royal pain in the a$se!
Lösung
FIND "[ERR" "text.csv" sets ERRORLEVEL to 0 if at least one [ERR
is found, and 1 if no [ERR
is found. You need a way to invert the logic.
If all you want to do is immediately return 0 if no [ERR
found, or 1
if at least one [ERR
found, then I would use the following:
find "[ERR" "test.csv" >nul && exit /b 1 || exit /b 0
If you want to capture the result in a variable to be returned later, then:
find "[ERR" "test.csv" >nul && set "err=1" || set "err=0"
or
find "[ERR" "test.csv" >nul
set /a "err=!%errorlevel%"
When you are ready to return the result
exit /b %err%
Below is my original answer that was accepted, yet was embarrassingly wrong :-(
Thanks Corey for pointing out the logic error. As he says in his comment, the faulty code below will only report an error if all of the lines have the [ERR
text.
FIND will set the ERRORLEVEL to 0 if found, 1 if not found. To reverse the logic, simply use the /V option.
find /v "[ERR" "test.csv" >nul
If you have a variable set that indicates the errorlevel, then you can use EXIT /B to set the ERRORLEVEL
set err=1 exit /b %err%
Andere Tipps
Note that the IF command has the logic that it returns true if ERRORLEVEL is greater than or equal to the following number! So
IF ERRORLEVEL 0 (...
returns true for all FIND commands. What you need if you only want to test if a phrase is in a file:
find "string" "test.txt" > NUL & IF NOT ERRORLEVEL 1 ECHO String was found
Took me ages to work that out!
This is the logic I've used in a BAT file previously.
find "string" "test.txt" > NUL & IF ERRORLEVEL 1 (
ECHO String was NOT found
) ELSE (
ECHO String was found
)
You could put whatever commands you wish inside the IF/ELSE blocks.