How to get ERRORLEVEL for each command in FOR LOOP?

2.2k views Asked by At

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

There are 1 answers

4
sohaib On BEST ANSWER

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.