批处理文件 - 将字符串比作整数不起作用

时间:2013-07-05 19:14:13

标签: batch-file

我试图将整数文件夹名称与变量进行比较。文件夹名称都是整数值。例如,在文件夹“VersionedFolders”中存在子文件夹“95”,“96”,最多为“100”。

我的脚本如下:

@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       
    )
)

输出如下:

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.

最后一次迭代是问题存在的地方,因为100> 99.

注意dir / B“%PATH_TO_VERSION_FOLDER%”的输出是

100
95
96
97
98
99

任何想法为什么“如果100 LEQ 99”正在回归?

2 个答案:

答案 0 :(得分:3)

问题是DELAYED EXPANSION。

解析for ...%%a...时,此时currentversion的值将替换为代码。

使用!currentversion!获取RUN-TIME值(调用delayedexpansion,因为你有...)

(另外:要分配值,请使用SET VAR=VALUE而不是SET %VAR=VALUE

答案 1 :(得分:1)

这是你的意图吗?你还有变量前面/后面的空格和变量名称,这是需要注意的地方。

@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