3

I am comparing a list of files from 2 folders using a windows batch file. It prints the results whether PASS/FAIL.

Current Working Batch File:

for /F "tokens=*" %%f in (list.txt) do compare Folder1\%%f.png Folder2\%%f.png

If there are 3 files, the output after running this command would look like this:

PASS
FAIL
PASS

If I echo the %ERRORLEVEL% here, it would return 0 because the for loop ran fine.

echo %ERRORLEVEL%

0

My Requirement

Echo the result of each command in the FOR loop instead.

My Expected Output

0
1
0

How do I change the batch file to achieve this?

1 Answer 1

4

Assuming that FAIL changes the ERRORLEVEL, Use & to echo ERRORLEVEL for each command:

SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%f in (list.txt) do compare Folder1\%%f.png Folder2\%%f.png & echo !ERRORLEVEL!
ENDLOCAL

OUTPUT:

PASS
0
FAIL
1
PASS
0

I assume PASS/FAIL is the output of your compare utility. To hide this output use redirection > to NUL like this:

SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%f in (list.txt) do compare Folder1\%%f.png Folder2\%%f.png > NUL & echo !ERRORLEVEL!
ENDLOCAL

OUTPUT:

0
1
0

From documentation:

& : command1 & command2

Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

Sign up to request clarification or add additional context in comments.

4 Comments

This cannot work, because: 1. you need delayed expansion for !ErrorLevel! to get the ErrorLevel of the iteration; otherwise, the ErrorLevel present when reading the entire command line is returned; 2. && prevents non-zero ErrorLevels to be returned, you must use & instead;
@aschipfl, sorry for overlooking. I have updated the answer and added documentation as well. Thanks for pointing out.
I tried this. Getting the below output: PASS !ERRORLEVEL! FAIL !ERRORLEVEL! PASS !ERRORLEVEL!
@InsecureNoob, then you forgot to enable delayed expansion obviously...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.