-2

I have the following in a .bat. I am trying to pull the most recent file (as the file name changes each time a new file is generated) from a network drive and copy it to a folder on my desktop changing the name so I can hit it from an outside DB. Unfortunately I am relatively new with .bat files and cannot figure out how to pull the latest file instead of the defined file below. I will turn this around and put it into a task scheduler to pull the file every thirty minutes.

copy \\fipr01\SNAP\P161201135302673.tmp C:\Users\ddtacopy\Desktop\AutoCopy\SNAP.txt
aschipfl
  • 33,626
  • 12
  • 54
  • 99
Darren Tracy
  • 37
  • 1
  • 7

1 Answers1

1

You could use dir to get a list of files sorted by age, take the newest file and then copy it:

pushd "\\fipr01\SNAP"
for /F "delims=" %%F in ('
    dir /B /O:D /T:C "*.tmp"
') do (
    set "NEWEST=%%F"
)
copy /Y "%NEWEST%" "C:\Users\ddtacopy\Desktop\AutoCopy\SNAP.txt"
popd

How does it work?

  • pushd creates a temporary drive letter that points to the given network path and changes to that; this is done because many batch commands do not support network paths;
  • dir /B /O:B /T:C returns a list of files *.tmp in the current directory, with the newest item last; /T:C tells dir to sort by the creation date; omit that if you want to use the modification date;
  • the for /F loop around dir reads its output and enumerates all the items; for each iteration it assigns the currently iterated item to variable NEWSET the set; the variable value is overwritten each time, so since the newest item is listed as last, NEWEST contains that one finally;
  • at that point the retrieved item is copied; the /Y tells the copy command to overwrite an already existing target file without asking; if you want a prompt to appear, change it to /-Y;
  • popd cleans up the temporary drive letter created by pushd and returns to the former directory;
aschipfl
  • 33,626
  • 12
  • 54
  • 99