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


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?

Best Solution

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 "*.*" /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:

SET DatabaseBackupPath=\\virtualserver1\Database Backups

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',  ^