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

Viewed 197782

I need to copy the newest file in a directory to a new location. So far I've found resources on the forfiles command, a date-related question here, and another related question. I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place?

10 Answers

The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

FOR /F "delims=" %%I IN ('DIR "*.*" /A-D /B /O:D') DO SET "NewestFile=%%I"

Now you can reference %NewestFile% throughout the rest of your bat file.

For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups

echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"

sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM  DISK = N'D:\%NewestFile%' ^
WITH  FILE = 1,  ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^
NOUNLOAD,  STATS = 10"

Windows shell, one liner:

FOR /F "delims=" %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY "%%I" <<NewDir>> & EXIT

I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:

cp `ls -t1 | head -1` /somedir/

Which will list all files in the current directory sorted by modification time and then cp the most recent to /somedir/

This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.

Obviously, replace new_file_loc with whatever your new file location will be.

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0

The previous answers compares the modification date and NOT the creation date. Here is an example of a script that compares based on the creation date and time:

set origFolderPath=..\Source\Customization.Solution
set distFolderPath=.\PublishCustomization.Solution

FOR /F "tokens=*" %%I IN ('DIR "%origFolderPath%\*.zip" /T:C /B /O:D') DO SET "NewestFile=%%I"
copy %origFolderPath%\%NewestFile%  %distFolderPath%

The trick is that /A-D that is used in previous answers checks the modification date which can be the same for all edited files if you run the script on grabbed files from a source control system like tfs and then a wrong answer will be yeilded. /T:C compares the creation date time instead which might be a solution in such cases.

Copy most recent files based on date from one directory to another directory

echo off
rem copying latest file with current date from one folder to another folder
cls
echo Copying files. Please wait...
:: echo Would you like to do a copy?
rem pause
for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
:: Pad digits with leading zeros e.g Sample_01-01-21.csv
    set yy=%year:~-2%
:: Alternate way - set datestr=%date:~0,2%-%date:~3,2%-%date:~6,2%
set datestr=%day%-%month%-%yy%
:: echo "\\networkdrive\Test\Sample_%datestr%.csv"
rem copy files from src to dest e.g copy <src path> <dest path>
copy "D:\Source\Sample_%datestr%.csv" D:\Destination
echo Completed
rem pause

Save the above code with .bat file format and Change the directory as per your needs and run the batch file.

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

Related