Reputation: 15
I am trying to copy the newest file based on the time, I tried the below script, but it is copying all the files not the latest file:
FOR /F %%I IN ('DIR "%FILE1%\CC*.txt" /B /O:-D /s') DO COPY %%I C:\Hyp\New\
For ex.:
xyz1.txt -- 4:23 xyz2.txt -- 4:25 xyz3.txt -- 4:30
But I need to copy only the latest file i.e. 4:30
, kindly assist (not all the files).
Upvotes: 1
Views: 604
Reputation: 34899
You are quite close. Instead of copying inside the bode of the FOR
loop, store the file in a variable (say LATEST
), which will be overwritten every iteration. After the loop has finished, the newest file is stored in the variable, supposing you define the sort order like /O:D
(oldest file listed first).
This is the fixed script:
FOR /F %%I IN ('DIR "%FILE1%\CC*.txt" /B /A:-D /T:W /O:D /S') DO SET "LATEST=%%~I"
COPY "%LATEST%" "C:\Hyp\New\"
I added the filter /A:-D
in order to enumerate files only (no directories).
Furthermore, I added the /T
option which allows to choose which file date to use: state W
for last modification (default), C
for creation, or A
for last access.
Upvotes: 1