Bob
Bob

Reputation: 785

Batch File - Comparing strings as integers not working

I am trying to compare integer folder names to a variable. The folder names are all integer values. For example, in folder "VersionedFolders" exist sub folders "95", "96", up to "100".

My script is as follows:

@echo off
setlocal ENABLEDELAYEDEXPANSION


SET %PATH_TO_VERSION_FOLDER=VersionedFolders
SET %CurrentVersion = 99

for /f %%a in ('dir /B "%PATH_TO_VERSION_FOLDER%"') do (        
    if %CurrentVersion% LEQ %%a (
        echo CurrentVersion !CurrentVersion! is less than or equal to %%a.      
        set CurrentVersion=%%a 
    ) else (
        echo CurrentVersion !CurrentVersion! is not less than or equal to %%a       
    )
)

The output is as follows:

CurrentVersion 99 is less than or equal to 100.
CurrentVersion 100 is not less than or equal to 95.
CurrentVersion 100 is not less than or equal to 96.
CurrentVersion 100 is not less than or equal to 97.
CurrentVersion 100 is not less than or equal to 98.
CurrentVersion 100 is less than or equal to 99.

The last iteration is where the problem exists since 100 > 99.

Note the output of dir /B "%PATH_TO_VERSION_FOLDER%" is

100
95
96
97
98
99

Any ideas why "if 100 LEQ 99" is returning true?

Upvotes: 2

Views: 990

Answers (2)

Magoo
Magoo

Reputation: 79983

The problem is DELAYED EXPANSION.

When the for ...%%a... is parsed, the value of currentversion as it stands at that time is substituted into the code.

Use !currentversion! to obtain the RUN-TIME value (with delayedexpansion invoked, as you have...)

(Also: to assign a value, use SET VAR=VALUE not SET %VAR=VALUE)

Upvotes: 3

foxidrive
foxidrive

Reputation: 41234

Is this what you intended? You also had spaces in front/behind variables and variable names, which is something to watch for.

@echo off
setlocal ENABLEDELAYEDEXPANSION

SET PATH_TO_VERSION_FOLDER=VersionedFolders
SET CurrentVersion=0

for /f %%a in ('dir /B /ad "%PATH_TO_VERSION_FOLDER%"') do (        
    if !CurrentVersion! LEQ %%a (
        echo CurrentVersion !CurrentVersion! is less than or equal to %%a.
    ) else (
        echo CurrentVersion !CurrentVersion! is greater than %%a.
    )
        set CurrentVersion=%%a
)
pause

Upvotes: 1

Related Questions