Search code examples
batch-filecopyxcopy

Batch file to copy 2 most recent files into another folder


I've been looking on the web and can't seem to find what I'm looking for. Before I begin I'm by no means an experienced command line user so please be gentle.

I need a batch file that will copy the two most recent files from one directory to the other, I then need the files that were in the destination folder to be removed which just leaves those two newest visible.

It's worth noting that I have tried the /d command (not including a date) however, this starts copying all files rather than those that are the most recent.

Please help?

Thanks


Solution

  • Your description is a bit upside down.
    It's a bit clumsy to first copy files to the destination and then delete all except the two new ones.

    • You could evaluate the two files and remember the names ( in an array )
    • delete all files in dest
    • and finally copy the remembered files

    Impertinently stealing npocmaka's code as a base:

    @Echo off
    setlocal enableDelayedExpansion
    set "source=c:\source_folder"
    set "target=c:\target"
    
    PushD "%source%"
    set "counter=0"
    for /f "tokens=* delims=" %%A in ('dir "*.bak" /b /o:-d /t:w') do (
       set /a counter+=1
       Set Copy[!counter!]=copy "%%~fA" "%target%\"
       if !counter! equ 2 goto :break
    )
    :break
    Del /Q "%target%\*"
    For /L %%C in (1,1,%counter%) Do !Copy[%%C]!
    PopD