Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: %errorlevel% will have different result in my batch file and in DOS command.  (Read 5298 times)

0 Members and 1 Guest are viewing this topic.

Stan Huang

    Topic Starter


    Beginner

    • Experience: Experienced
    • OS: Windows 7
    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  <dir1> <dir2>
    :: 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
             )
          )
       )

    Salmon Trout

    • Guest
    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%