views:

47

answers:

2

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

http://stackoverflow.com/questions/97371/batch-script-to-copy-newest-file

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 for 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
A: 

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.

bde
Thankyou so much, that works! Although the only thing is that it isn't renaming the file when it moves.Unfortunately, for reasons that are too long winded to go into here, the source directory will need to keep the '!' in its name.Any other thoughts on how to have the script simultaneously rename the file would be very much appreciated!
david.murtagh.keltie.com
The other recently posted answer has a good way to rename the file with the copy command. belisarius also has a good point that you should explicitly disable delayed expansion before calling pushd, just in case your script is ever called with delayed expansion already enabled.
bde
A: 

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 :)

belisarius
That is brilliant, it works perfectly!Many thanks to you both!
david.murtagh.keltie.com