1

I need to move, cut & paste, the newest file in a directory to a newly created folder location. The file is created by a separate program that I do not have permissions. The new directory location is created by a batch file which has been copied below. I found some basis to follow from code samples. I'm just having a bit of trouble putting the pieces together. How do I move the newest file from a directory location to new directory location?

:: Auto directory date batch (MMDDYYYY format)
:: First parses month, day, and year into mm , dd, yyyy formats and then combines to be DDMMYYYY
:: Setups %date% variable
:: @author Deepu Mohan Puthrote www.deepumohan.com
@echo off
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%yyyy%%mm%%dd%
echo New folder name %date%
MKDIR %date%

I added to first .bat to move file to new directory, as my attempt to move the file to the new directory but I got an error

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY %%I <<%date%>>
pause

<< unexpected at this time

2 Answers 2

3

Try this:

for /f "tokens=*" %%i in ('dir /od /b /a-d') do set "file=%%~i"
move "%file%" "%date%"

BTW: do not use default environment variable names for batch variables (date).

0
2

You're on the right track with your FOR loop. You'll just want to do a MOVE rather than COPY, and then quit the loop after processing the first item.

FOR /F "delims=" %%I IN ('DIR . /B /O:-D /A-D') DO (
    MOVE "%%I" "%date%"
    GOTO :EOF
)

I've added /A-D in the DIR to exclude directories, and removed the << and >>. (I'm not sure why those were in there to begin with.)

2
  • I am not sure if this should be a new question or not, but what would need to change if I wanted to grab all the files of the current date to this directory, instead of just the newest file. Commented Mar 15, 2013 at 15:19
  • 1
    Ah, that's actually easier! :-) Robocopy is your friend. Robocopy is included in Vista and newer, and is available for download for older OSes. robocopy "from\dir" "to\dir" /maxage:1 /mov will move all files that are one day old. Type robocopy /? for help. Commented Mar 15, 2013 at 16:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.