简体   繁体   中英

How do I write a Windows batch script to copy the newest file from a directory into new folder?

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

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

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 /AD in the DIR to exclude directories, and removed the << and >> . (I'm not sure why those were in there to begin with.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM