0

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?

5
  • How do you know which files are considered "newest?" From the original question, it makes sense that it would only copy 1 file, as only 1 file can truly be the newest. Can you provide an example of the folder structure and sample files and describe the behavior you expect please? Commented Dec 23, 2014 at 16:56
  • Newest is based on the modified date of the file.
    – Arun.K
    Commented Dec 23, 2014 at 17:00
  • If you're going based on the modified date, how can you have 2 "newest?" One file will nearly always be SLIGHTLY newer than another… Am I misunderstanding something? Commented Dec 23, 2014 at 17:02
  • Yes you are correct. Say the files were modified y'day, so i need both the files that were modified yday? How can i do that?
    – Arun.K
    Commented Dec 23, 2014 at 17:37
  • Can you please post an example of the potential files in a folder, their date modified, and the expected output? Commented Dec 23, 2014 at 19:35

1 Answer 1

1

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.

5
  • This is not working. No files are copied and throwing error that the network path is not found.
    – Arun.K
    Commented Dec 23, 2014 at 17:40
  • The error says destination path C:\Users\xyz\Desktop\DS\datafiles not valid. It is working though with my earlier code.
    – Arun.K
    Commented Dec 23, 2014 at 18:15
  • Did you leave "%target%" quoted? Try putting @echo on just before the for /f loop and see what the last command attempted is before the failure.
    – rojo
    Commented Dec 23, 2014 at 18:19
  • From ECHO on what i understand is the issue with the target C:\Users\egopaa02\Desktop\DS\nfc_data_files\file.xml is invalid. Something to do with this "%source%\%%~fI" "%target%". Its taking the xml file also as target.
    – Arun.K
    Commented Dec 23, 2014 at 18:36
  • I'm so sorry. That was a silly error on my part. Try the new edit.
    – rojo
    Commented Dec 23, 2014 at 18:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.