简体   繁体   中英

How to get ERRORLEVEL for each command in FOR LOOP?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM