问题
I want to create a batch to check if the file have been modified to today's date, what i did was to "bring in a system's date and compare it with the modified date, if they match, then trigger something. My batch file works well and displays two right dates, but the IF statement saying the date mismatch.
@ECHO OFF
for /f "tokens=1,2,3,4 delims=. " %%i in ('date /t') do set date=%%k%%j
echo %date%
pause
FOR %%a IN (D:\MyFile.txt) DO SET FileDate=%%~ta
set DATEONLY=%FileDate:~0,10%
echo %DATEONLY%
pause
if DATEONLY==date (
echo date ok
)
else (
cls
ECHO Wrong
)
PAUSE
回答1:
There are the following problems:
- do not use variable name
date
as this is a built-in variable containing the current date (typeset /?
for help); - the first
for
statement is useless, because%date%
is already available; - the strings
DATEONLY
anddate
are compared literally in yourif
statement, you need to state%DATEONLY%==%date%
instead; - the
else
statement must be in the same line as the closing parenthesis of theif
body (typeif /?
for help);
So try this:
@ECHO OFF
echo %date%
pause
FOR %%a IN (D:\MyFile.txt) DO SET FileDate=%%~ta
set DATEONLY=%FileDate:~0,10%
echo %DATEONLY%
pause
if %DATEONLY%==%date% (
echo date ok
) else (
ECHO Wrong
)
PAUSE
Note: Regard that all those dates in the batch file are locale-dependent.
回答2:
Here is a completely different approach:
forfiles /P . /M MyFile.txt /D +0 /C "cmd /C echo @fdate @file"
The forfiles
command is capable of checking the file date. In the above command line, it:
- walks through the current directory (
.
), - lists all files named
MyFile.txt
(of course there is onlyone), - but only if it has been modified
+0
days after today, - and then executed the command line after the
/C
switch.
If MyFile.txt
has been modified today (or even in future), the given command line is executed;
if it has been modified earlier than today, an error message is displayed and ERRORLEVEL
is set to 1
.
Notice that forfiles
is not a built-in command and might not be available on your operating system.
来源:https://stackoverflow.com/questions/31527032/batch-file-check-file-get-updated-to-todays-datesystem-date