3

The batch command below will get me the newest file in a folder, however I'm only looking for files with a specific extension. Can anyone explain how to specify the extension (i.e. .jpg)

FOR /F "delims=|" %%I IN ('DIR "C:\Jenkins\Releases\C9metro" /B /O:D') DO SET NewestFile=%%I
NealR
  • 9,361
  • 54
  • 153
  • 287

2 Answers2

4

I suggest to use the following lines:

FOR /F "eol=| delims=" %%I IN ('DIR "C:\Jenkins\Releases\C9metro\*.jpg" /A-D /B /O-D /TW 2^>nul') DO (
    SET NewestFile=%%I
    GOTO FoundFile
)
ECHO No *.jpg file found!
GOTO :EOF

:FoundFile
ECHO Newest *.jpg file is: %NewestFile%

The parameter /A-D makes sure ignoring subdirectories which unusually end by chance also with the string .jpg.

The parameter /B turns on bare format returning in this case just the file name without path by command DIR.

The parameter /O-D results in getting the found files by DIR listed by date in reverse order from newest to oldest.

And parameter /TW makes sure the last modification time (write access) is used for listing the found JPEG files in date order.

The loop is exited on first found file matching the wildcard pattern *.jpg making this method faster than assigning all file names to variable NewestFile up to last file found.

Mofi
  • 42,677
  • 15
  • 72
  • 128
2

It's early... figured this one out:

'DIR "C:\Jenkins\Releases\C9metro\*.jpg"
NealR
  • 9,361
  • 54
  • 153
  • 287