Search code examples
batch-filewindows-shell

Get absolute path of newest file containing string in filename in batch script


I have a batch file that I would like to pick up the newest "manifest" file, so I was hoping to be able to use a for loop for that, but I'm not sure of the correct syntax.

This is what I have:

for /R %imagePath% %%F in (*.manifest.*) do (set manFile=%%F)

Which does the correct thing to return "C:/some/path/to/file.manifest.ext", but not necessarily the newest one. I see other questions like this one that use dir, but then I don't get the entire path. My attempt at doing this with dir looks like:

for /R %imagePath% %%F in ('dir /od *.manifest.*.*') do (set manFile=%%F)

This doesn't give me the output I was expecting.

What is the best way to accomplish this?


Solution

  • set "manFile="
    for /f "tokens=2,*" %%a in ('
        robocopy "%imagePath%" "%temp%" *.manifest.* /is /l /nocopy /s /njh /njs /ndl /nc /ns /ts
        ^| sort /r
    ') do if not defined manFile set "manFile=%%b"
    

    This uses a for /f to process the output of a robocopy command that will generate a list of the matching files with a UTC timestamp that will be reverse sorted so the newest file will be the first in the list.