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"
SET "smart_server=Z:\JUL2017"
Your actual variablesmart_server
contains the path plus the apostrophes. alsoSET "NewestFile=%%I"
as it may contain spaces. andcopy "%NewestFile%" ...
as it is fully qualified%smart_server%
variable, as mentioned above, you can improve yourDIR
command further by removing the pipe toFIND
,'DIR/B/S/A-D-S-L/OD "%smart_server%\*ASN*.txt"'
. I added the.txt
extension because you said text file, please adjust if necessary.I need to find the latest file containing the text 'ASN'
. But I think the OP will clarify that ;-).