Copying files based on date modified in batch file

后端 未结 1 1015
终归单人心
终归单人心 2021-01-16 20:45

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 t

相关标签:
1条回答
  • 2021-01-16 21:25

    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%"
    )
    
    0 讨论(0)
提交回复
热议问题