1.

Solve : %errorlevel% will have different result in my batch file and in DOS command.?

Answer»

Below is my BATCH file for comparing two folders. I would like to compare each files under two folders to make sure they are the same. I used 'fc' to compare files and then CHECK the result. The strange thing is that I usually got non-zero %errorlevel% in this batch file when it compares two identical files. But if I did the same comparison at DOS command PROMPT, I got expected result. How come?

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:cmpdir dir1 DIR2
::
:: Func: Compare files and folders in two dir1 & dir2
::
:: Args: %1 the first folder to be compared
:: %2 the SECOND folder to be compared
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:cmpdir
:: setlocal ENABLEEXTENSIONS
@echo off

FOR /R "%1\" %%G in (*) DO (
if not exist %2\%%~nG%%~xG (
echo "%2\%%~nG%%~xG disappeared"
exit /b 255
) else (
if not exist "%1\%%~nG%%~xG\" (
echo "%1\%%~nG%%~xG compared to %2\%%~nG%%~xG"
fc /b %1\%%~nG%%~xG %2\%%~nG%%~xG
echo "errorlevel = %errorlevel%"
if %errorlevel% neq 0 (
echo "%2\%%~nG%%~xG corrupted"
exit /b 255
)
)
)To set and also expand a variable inside a code block with parentheses (such as a FOR loop or extended IF block) you need to use delayed expansion.

1. Precede code section (or entire batch) with setlocal enabledelayedexpansion
2. Use exclamation marks, not percent signs, with variable i.e. !errorlevel! not %errorlevel%



Discussion

No Comment Found