Arun.K
Arun.K

Reputation: 103

Copy newest or latest files using .bat command

I have to copy the latest or newest files from a server to another server.

I have a code like this

@echo off
set source="\\tsclient\F\Project Documentation"
set target="C:\Users\xyz\Desktop\DS\datafiles"

FOR /F "delims=" %%I IN ('DIR %source%\*.xml /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

The issue is, this will only copy 1 file, there are two new files. How to copy the second one?

Upvotes: 0

Views: 183

Answers (1)

rojo
rojo

Reputation: 24466

You could do it with delayed expansion and a loop variable like this:

@echo off
setlocal enabledelayedexpansion

set "source=\\tsclient\F\Project Documentation"
set "target=C:\Users\xyz\Desktop\DS\datafiles"

set loop=1
FOR /F "delims=" %%I IN ('DIR "%source%\*.xml" /A:-D /O:-D /B') DO (
    COPY "%source%\%%~nxI" "%target%"
    echo %source%\%%~nxI
    if !loop! equ 2 GOTO END
    set /a loop+=1
)
:END
TIMEOUT 4

It'll always copy 2 files, though. If you have only one new file, you'll still copy two.

Upvotes: 1

Related Questions