且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在批处理脚本中比较文件的时间戳?

更新时间:2023-01-22 14:04:07

您可以使用一行批处理脚本来查找两个文件的较新版本.只需按日期顺序列出文件,最旧的开始,这意味着列出的最后一个文件必须是较新的文件.因此,如果您每次都保存文件名,则变量中的姓氏将是最新文件.

You can find the newer of two files with one line of batch script. Just list the files in date order, oldest first, which means the last file listed must be the newer file. So if you save the file name each time, the last name put in your variable will be the newest file.

例如:

SET FILE1=foo.txt
SET FILE2=bar.txt
FOR /F %%i IN ('DIR /B /O:D %FILE1% %FILE2%') DO SET NEWEST=%%i
ECHO %NEWEST% is (probably) newer.

不幸的是,这不能解决相同的日期戳问题.因此,我们只需要首先检查文件是否具有相同的日期和时间戳:

This unfortunately doesn't cope with the date stamps being the same. So we just need to check if the files have the same date and time stamp first:

SET FILE1=foo.txt
SET FILE2=bar.txt

FOR %%i IN (%FILE1%) DO SET DATE1=%%~ti
FOR %%i IN (%FILE2%) DO SET DATE2=%%~ti
IF "%DATE1%"=="%DATE2%" ECHO Files have same age && GOTO END

FOR /F %%i IN ('DIR /B /O:D %FILE1% %FILE2%') DO SET NEWEST=%%i
ECHO Newer file is %NEWEST%

:END