How do I write a Windows batch script to copy the newest file from a directory?
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