Solved Batch copy last x modified files

June 26, 2011 at 10:00:42
Specs: Windows XP, 2.5GHz/4GB
Hello Experts,

I would like to copy only the 5 last modified files in a directory with a windows batch file. If there are less than 5 files then it should copy only the available files. If there are no files then the batch should ignore.

Is this possible without too much programming?


See More: Batch copy last x modified files

Report •

June 26, 2011 at 20:20:14
Greetings Peter. Am sure I don't qualify as an "expert" but know that your requirement can be met in a batch script. Do you want to be involved in writing the script or do you want the script written for you?


Please come back & tell us if your problem is resolved.

Report •

July 2, 2011 at 05:54:57
Hello Wahine,

Actually I would like a batch code example.

I know files can be copied by its date with xcopy using a single line of code. But I want to set an absolute number of files to be copied independent of the modified date.


Report •

July 4, 2011 at 02:53:21
✔ Best Answer
Peter - test this please.

@echo off&echo y |del %temp%\filescopied\*.*
setlocal enabledelayedexpansion

pushd %temp%\files\||echo Pushd failed - job terminated&&exit /b

for /f "tokens=*" %%1 in ('dir /a-d^|find /i "file(s)"') do (
    set line=%%1
        for /f "tokens=1*" %%A in ("!line!") do (
            set files=%%A

if %files% lss 1 (
   echo No files to copy..
   exit /b

if %files% lss 6 ( 
   dir /b /a-d>%temp%\files2copy.txt
   goto copyit

dir /b /a-d /tw /o-d>%temp%\files2copy.txt

set nbr=5
for /f "tokens=*" %%1 in (%temp%\files2copy.txt) do (
    set /a nbr-=1
    copy "%temp%\files\%%1"  "%temp%\filescopied\">nul
    if !nbr! lss 1 (
    goto finis



echo.Files copied:
dir /a-d %temp%\filescopied\*.*|find "/"

del %temp%\files2copy.txt>nul

Please come back & tell us if your problem is resolved.

Report •

Related Solutions

July 6, 2011 at 12:42:33
Hi Wahine,

Thanks! Your code works like a charm!

I didn't know it would take this amount of code to do the job. The writing to a temporary text file is brilliant and I wouldn't have come up with that myself.


Report •

July 6, 2011 at 14:12:27
Peter - The amount of code is probably excessive, it's just one way of achieving your objective and lay it out in a manner which I thought would be easy to understand, there's nothing worse than complicated codings which the user cannot come to grips with. You could now go on and cut it back if you wish to.

Many thanks for coming back to report your success.


Please come back & tell us if your problem is resolved.

Report •

Ask Question