How to code a batch file to copy and rename the most recently dated file?
I'm trying to code a batch file to copy only the most recently dated file in a given folder to another directory on the local machine, and simultaneously rename it as it does.
I've found a very similar question here
How do I write a Windows batch script to copy the newest file from a directory?
and have managed to cobble together the below code from other forums too, but have hit a brick wall as it only results in the batch file itself being copied to the destination folder. It doesn't matter to me where the batch file itself sits in order f开发者_开发知识库or this to run.
The source folder is C:! BATCH and the destination folder is C:\DROP
The code is below, apologies if this is a glaringly obvious answer but it's literally the first foray into coding batch files for me... Thanks!
@echo off
setLocal EnableDelayedExpansion
pushd C:\! BATCH
for /f "tokens=* delims= " %%G in ('dir/b/od') do (set newest=%%G)
copy "!newest!" C:\DROP\
PAUSE
Try moving the pushd
command above the setLocal
command.
My guess is that the "!" character has a special meaning for delayed expansion, so you may not be able to use it as part of a path name after you turn on delayed expansion.
You could also remove the exclamation point from your path if you don't really need it, that might be easier.
I think this small mods enable your script to do what you want
@echo on
setLocal DisableDelayedExpansion
pushd "C:\! BATCH"
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%G in ('dir/b/od') do (set newest=%%G)
copy %newest% C:\DROP\newname.txt
PAUSE
POPD
newname.txt ... is the new name :)
精彩评论