Kranthi
Kranthi

Reputation: 23

Compare current date with file modified date in batch file

I have a requirement to create a batch file and that should work in windows 2003 server.

  1. I have source folder "c:\Source" and destination folder "c:\Destination".
  2. I want to check all the file modified dates in source folder:

    • If the file modified date is less than current date then that file will move into destination folder
    • Otherwise, do nothing.

Note: as my server is production server so, I am unable to install Resource kit and robocopy.exe. The only way is write the batch script.

Robocopy and forfiles are not working in Windows2003 server.

Upvotes: 2

Views: 9634

Answers (1)

rojo
rojo

Reputation: 24466

Update

Since you have forfiles on your server, this is easy. To check for files older than 1 day old, just use forfiles /D -1. For files over 2 days old, /D -2.

forfiles /D -2 /M *.log /P C:\Source /C "cmd /c move @file c:\Destination"

Enter forfiles /? in a console window for full syntax.


Original answer

Consider revising your requirement. Instead of saying "If file modified date is less than the current date", you should say, "If file modified date does not equal current date". That absolves you from having to do date math, and makes your task profoundly simpler. After all, the last modified date is not going to be a date in the future, right?

After that, it's a simple matter of scraping today's date from %date% and comparing it with the date from each file's %%~tX substitution property in a for loop. Type help for in a console window and see the last two pages for more information about this syntax.

I don't think there will be any locale date formatting issues with this. As long as your system's %date% variable is in the format of dayOfWeek Date and %%~tX is formatted as Date Time etc. then this script should work regardless of whether you handle dates locally as MM/DD/YYYY or YYYY/MM/DD or DD/MM/YYYY or something else. I hope.

@echo off
setlocal enableextensions

set "source=c:\Source"
set "destination=c:\Destination"

:: store today's date in %today%
for /f "tokens=2" %%I in ('echo %date%') do set "today=%%I"

for %%I in ("%source%\*") do (
    rem :: scrape MM/DD/YYYY from %%~tI
    for /f %%a in ('echo %%~tI') do (

        rem :: compare the two dates
        if "%%a" neq "%today%" (
            echo %%~nxI: %%a does not equal %today%.  Moving.
            >NUL move /y "%%~fI" "%destination%"
        ) else (
            echo %%~nxI: %%a equals %today%.  Skipping.
        )
    )
)

Upvotes: 2

Related Questions