Batch file check file get updated to today's date(System Date)

假如想象 提交于 2019-12-25 14:38:41

问题


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 (type set /? for help);
  • the first for statement is useless, because %date% is already available;
  • the strings DATEONLY and date are compared literally in your if statement, you need to state %DATEONLY%==%date% instead;
  • the else statement must be in the same line as the closing parenthesis of the if body (type if /? 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!