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:
:Variables
SET DatabaseBackupPath=\virtualserver1Database 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 FilesMicrosoft SQL ServerMSSQL.1MSSQLExample.mdf', ^
MOVE N'Example_CS_log' TO N'C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLExample_1.LDF', ^
NOUNLOAD, STATS = 10"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…