Search code examples
windowsbatch-filelast-modified

Windows batch script copy file last modified


I'm trying to write a quick batch script to look at the last modified date of one file and compare it to the last modified date of a few others, and if it's greater than those other lastmods, it copies the files to those directories. This is what I have so far:

@echo off
for %%a in ([srcFile]) do set lastmodSrc=%%~ta
echo lastmodSrc
for %%a in ([dstFile1]) do set lastmodDst1=%%~ta
for %%a in ([dstFile2]) do set lastmodDst2=%%~ta
for %%a in ([dstFile3]) do set lastmodDst3=%%~ta
for %%a in ([dstFile4]) do set lastmodDst4=%%~ta

if lastmodSrc GTR lastmodDst1 xcopy [srcFile] [dstDir1] /-y
if lastmodSrc GTR lastmodDst2 xcopy [srcFile] [dstDir2] /-y
if lastmodSrc GTR lastmodDst3 xcopy [srcFile] [dstDir3] /-y
if lastmodSrc GTR lastmodDst4 xcopy [srcFile] [dstDir4] /-y

pause

The square brackets are full path names. What it's doing right now is saving lastmodSrc and lastmodDst as just the strings (at least that's what it seems like it's what it's doing), and so it's not actually checking the mod dates. I'm woefully inadequate at batch scripting in Windows, figured someone here might be able to help. Thanks in advance!


Solution

  • Another approach that might be simpler (assuming I understand the goal) would be to use the /d option on xcopy. If that is given (without a date), it will copy the file only if the source is newer:

    xcopy /d srcfile dstfile