William Allen
William Allen

Reputation: 85

How to create a Batch File to copy the latest file based on time stamped filenames

I have a dir of CSV files which have a date time stamp in their file-name. I need to copy the file with the most recent date time in the name.

I am a newbie when it comes to batch scripting this is what I have so far, as you can see it copies a single file but does not loop through all file-names and only copying the most recent dated. Thanks for the help.

SET sourceDir=\\source\path
SET targetDir=\\target\path

copy "%sourceDir%\examplefile_20160111_010003.csv" "%targetDir%\newname.csv"

Upvotes: 0

Views: 132

Answers (1)

Stephan
Stephan

Reputation: 56180

there is no command that is able to do this. You have to use a little trick:

dir is able to sort alphabetically (that's exactly, what you want here) with /on parameter. /b gives you the filename only, /a-d excludes folders:

dir /a-d /on /b 

You want the last one. Get it with a for loop:

for /f "delims=" %%a in ('dir /a-d /on /b "%sourceDir%\examplefile_*.csv"') do set latest=%%a

Then you can copy "%sourceDir%\%latest%" "%targetDir%\newname.csv"

Upvotes: 1

Related Questions