0

我有一个将文件戳与脚本执行时间戳进行比较的代码。如果值不同,它会起作用,但是当值相同时,代码仍然不会跳出循环。我认为这背后的原因是脚本开头的语句 setlocal enableDelayedExpansion 。

该代码正确打印了 filesstamp 和 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 年 10 月 7 日下午 02:49
文件分钟 49
02
文件AMPM PM
2
文件时间长度 1
文件时间模块 2
结果 14
最终1449
**日期戳 201310071449
文件戳 201310071449**
该文件早于脚本执行时间。
24 延迟

欢迎提出建议。

提前致谢!

4

1 回答 1

0

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
)
于 2013-10-07T20:52:29.727 回答