Batch file 设置setlocal EnableDelayedExpansion时获取变量的新值

Batch file 设置setlocal EnableDelayedExpansion时获取变量的新值,batch-file,Batch File,我有一个比较filestamp和脚本执行时间戳的代码。 如果值不同,它就可以工作,但是当值相同时,代码仍然不会退出循环。 我认为这背后的原因是脚本开头的语句setLocalEnableDelayedExpansion 代码正确地打印filestamp和datestamp的值,但是if逻辑不能正常工作 @ECHO off setlocal EnableDelayedExpansion ECHO !fileTimemod!>x&FOR %%? IN (x) DO SET /A str

我有一个比较filestamp和脚本执行时间戳的代码。 如果值不同,它就可以工作,但是当值相同时,代码仍然不会退出循环。 我认为这背后的原因是脚本开头的语句setLocalEnableDelayedExpansion

代码正确地打印filestamp和datestamp的值,但是if逻辑不能正常工作

@ECHO off
setlocal EnableDelayedExpansion

ECHO !fileTimemod!>x&FOR %%? IN (x) DO SET /A strlength=%%~z? - 2&del x
echo filetimelength !strlength!
IF !strlength! EQU 1 (
    SET fileTimemod=0!fileTimemod!
echo fileTimemod !fileTimemod!
)



set FileM=!filestamp:~0,2!
set FileD=!filestamp:~3,2!
set FileY=!filestamp:~6,4!


set filestamp=!FileY!!FileM!!FileD!!final!

echo datestamp !datestamp!
echo filestamp !filestamp!
set newTimestamp=!filestamp!

 if  "!datestamp!" gtr "!filestamp!" (
 echo The file is older than the script execution time.

 ) else (
 echo Read the new file

)
**日志** **邮戳201310071449 文件戳记201310071435** 该文件比脚本执行时间早。 24延迟 计数器值为1 正在检查目录中是否存在该文件 2013年7月10日下午2:49 文件记录49 02 菲莱姆酒店 2. 文件时间长度1 fileTimemod 2 结果14 最终1449 **邮戳201310071449 文件戳201310071449** 该文件比脚本执行时间早。 24延迟 欢迎提出建议


提前谢谢

setlocal EnableDelayedExpansion
是解决方案,而不是问题

对于块内部的变量,您应该始终使用延迟语法,因为在执行块之前,百分比扩展将展开,而在执行行时,百分比扩展将展开

IF %strlength% EQU 1 (
  SET dateHMod=0%dateHMod%
  echo dateHMod %dateHMod%
)
echo dateHMod %dateHMod%
两个
echo
行显示不同的输出,第一行不带
0
,第二行带
0

IF !strlength! EQU 1 (
  SET dateHMod=0!dateHMod!
  echo dateHMod !dateHMod!
)
echo dateHMod !dateHMod!
这总是如预期的那样有效

在您的情况下,问题也可能是隐藏空间问题。
您的脚本和您的值按预期工作。
set
命令后的隐藏空格不可见,但会附加到变量中,因此在使用
set
时最好使用引号语法,这只会分配到最后一个引号之前的所有字符

setlocal EnableDelayedExpansion
set "datetime=201310071449" This won't be assigned
set "filestamp=201310071449"
echo datestamp -!datestamp!-
echo filestamp -!filestamp!-
set "newTimestamp=!filestamp!"

if  "!datestamp!" gtr "!newTimestamp!" (
    echo The file is older than the script execution time.
) else (
    echo Read the new file
)

我尝试将%更改为!但它仍然不起作用。时间戳相同,但如果条件不起作用。尝试整个批处理脚本。感谢您的指点。只需在echo语句中添加“我发现filestamp在结尾处得到了一个空格。datestamp”201310071637“filestamp”201310071634“我现在必须弄清楚该空格是如何被添加的。您应该将脚本简化为绝对必要的代码来演示该问题
setlocal EnableDelayedExpansion
set "datetime=201310071449" This won't be assigned
set "filestamp=201310071449"
echo datestamp -!datestamp!-
echo filestamp -!filestamp!-
set "newTimestamp=!filestamp!"

if  "!datestamp!" gtr "!newTimestamp!" (
    echo The file is older than the script execution time.
) else (
    echo Read the new file
)