Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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?

like image 844
Devrin Avatar asked Sep 18 '08 21:09

Devrin


People also ask

What is %% A in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I write a simple batch file to copy files?

Batch File to Copy FilesUse the command simply called "Copy." Generally, put the word copy on one line, followed by the original file and where you want it copied, such as "copy C:\Example\Example. txt C:\Example2\Example2. txt."

How do I create a batch file from a folder?

To create a Windows batch file, follow these steps: Open a text file, such as a Notepad or WordPad document. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause. Save your file with the file extension BAT, for example, test.


2 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" 
like image 128
Chris Magnuson Avatar answered Sep 26 '22 15:09

Chris Magnuson


Windows shell, one liner:

FOR /F "delims=" %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY "%%I" <<NewDir>> & EXIT 
like image 28
PabloG Avatar answered Sep 23 '22 15:09

PabloG