Findstr retuns an errorlevel code incorrect?
On first run the errorlevel
value is not being expanded to the runtime value.
In the second, the value of your first command is expanded.
In your command, you need to tell cmd to !expand!
the value of %variable/errorlevel%
at runtime, otherwise it will assume the current value, which occurs in the first and second
You can tell cmd (command line interpreter) to do it using /v:on |or| /v
:
cmd /v /c "findstr khry myfile.txt & echo\!errorlevel!"
In bat file use EnableDelayedExpansion
@echo off
setlocal EnableDelayedExpansion
findstr khry myfile.txt & echo\!errorlevel!
Try to take some time to better understand how cmd works in this answer below from @dbenham, and pay special attention to Phase 5:
- How does the Windows Command Interpreter [
cmd.exe
] Parse Scripts
Batch Scripts Parser
Phase 5) Delayed Expansion: Only if delayed expansion is on, the command is not in a parenthesized block on either side of a pipe, and the command is not a "naked" batch script (script name without parentheses, CALL, command concatenation, or pipe).Command Line Parser:
Phase 5) Delayed Expansion: only if DelayedExpansion is enabled: