iForce Redditch
iForce Redditch

Reputation: 11

Batch file to find and copy the latest file

There is a system that generates a txt file dump every 15 minutes with a different file name each time. I need to find the latest file containing the text 'ASN' and copy it to a folder where I can work on it.

so far I have this, but I cannot get it to copy any file.

SET smart_server='Z:\JUL2017'

FOR /F "delims=|" %%I IN ('DIR "%smart_server%" /S /B /O:D ^| find /i "ASN" ') DO SET NewestFile=%%I
copy "%smart_server%\%NewestFile%" "C:\htdocs\smart_asn_downloads\new" 

The source directory is a mapped drive I'm looking to copy it to a local drive.

Upvotes: 1

Views: 1478

Answers (1)

Andre Kampling
Andre Kampling

Reputation: 5631

The following will copy the files that contains the text ASN ignoring the case in the file itself not the file name:

@echo off
set "smart_server=Z:\JUL2017"

rem list all files (recursive) latest first
for /F "delims=|" %%I in ('dir "%smart_server%" /S /B /A-D /O:-D') do (
   find /i "ASN" "%%I" > nul
   rem success (errorlevel == 0)?
   if not errorlevel 1 (
      set "NewestFile=%%I"
   )
)
if defined NewestFile (
   rem addionally echoing the command due copy is not verbose
   echo copy "%NewestFile%" "C:\htdocs\smart_asn_downloads\new" 
   copy "%NewestFile%" "C:\htdocs\smart_asn_downloads\new" 
) else (
   echo Found no file!
)

There are several things I've changed.

1. set:
I changed the setting of the variable smart_server because your set contains the ' in the path.

2. The dir command:
The sorting with /O:D would show the oldest first to reverse the list use: /O:-D. Further exclude directories to show with dir because you can't search in them with find, use: /A-D.

3. The pipe to find:
It seems that the pipe to find does not work with spaces in a filename therefore I cut it out of the command and do it in the for loop. If the find is successful I set the NewestFile variable. I use find with /I so it ignores the case of the text.


If you need the script to copy files that contain ASN in the file name itself and ends with .txt you can use (this also ignores the case):

@echo off

set "smart_server=Z:\JUL2017"
for /F "delims=|" %%I IN ('DIR "%smart_server%\*ASN*.txt" /S /B /A-D /O:-D') DO SET NewestFile=%%I
echo copy "%NewestFile%" "C:\htdocs\smart_asn_downloads\new" 
copy "%NewestFile%" "C:\htdocs\smart_asn_downloads\new" 

Upvotes: 1

Related Questions