user922276
user922276

Reputation: 11

Copying files based on date modified in batch file

I am trying to copy files from one directory to another using a DOS batch script. The files I want to copy are the 4 or 3 latest files. That number will be static, but yet to be determined. Is there anyway to copy based on date modified?

Thank you

Upvotes: 0

Views: 16336

Answers (1)

Andriy M
Andriy M

Reputation: 77667

You could:

1) have the dir command sort files in the descending order of date modified;

2) use the output of the dir command in a `for loop to copy the corresponding files;

3) count to 3 (or 4) in the for loop to limit the number of files copied.

@ECHO OFF
SET "srcdir=D:\Source"
SET "tgtdir=D:\Target"
SET /A topcnt=3
SET /A cnt=0
FOR /F "tokens=*" %%F IN ('DIR /A-D /OD /TW /B "%srcdir%"') DO (
  SET /A cnt+=1
  SETLOCAL EnableDelayedExpansion
  IF !cnt! GTR !topcnt! (ENDLOCAL & GOTO :EOF)
  ENDLOCAL
  COPY "%srcdir%\%%F" "%tgtdir%"
)

Upvotes: 4

Related Questions