Search code examples
batch-filecmdrenamelast-modified

get last modification date of most recent file (recursive) and add the date to the folder name


i have a folder with subfolders and multiple files.

  • Root\Mainfolder1\Subfolder1\files
  • Root\Mainfolder1\Subfolder1\Subfolder2\files
  • Root\Mainfolder1\Subfolder3\files
  • Root\Mainfolder2\files
  • Root\Mainfolder2\Subfolder1\files

and the batchfile is inside the rootdir

i need to get the last modification date (yyyymmdd) for the most recent file throughout all folders. after getting the date, i need to add the date to the mainfolders name like: "Mainfolder (yyyymmdd)"

after that i need the same for the next mainfolder. basically i would end up with something like this:

Root\Mainfolder1 (yyyymmdd)
Root\Mainfolder2 (yyyymmdd)
Root\Mainfolder3 (yyyymmdd)

additional info: my system has another date format: dd.mm.yyyy (but i need the above format)

i want this to be a batchfile which i can place inside the root dir and then execute it to do what i have explained above. what code do i have so far? well near to nothing at all. nothing usable. only thing i found was how to list all modification dates (but they are not sorted or anything) with this:

dir /s /O:D /T:W /A:-D

and i cant find anything through the search function any suggestions are highly welcomed, thanks :)


Solution

  • Give this a try. I put some comments in the code to help you understand what is going on. Remove the ECHO in front of the RENAME command when you are satisfied with the output.

    @echo off
    setlocal enabledelayedexpansion
    
    REM List the directories first
    FOR /F "delims=" %%G IN ('dir /ad /b') DO (
        rem Change to the directory
        pushd "%%G"
        set "dt="
        set "newest="
        REM Get the date and time from the newest file from the folder.
        FOR /F "delims=" %%H IN ('dir /S /a-d /b 2^>nul') DO (
            REM by default the ~t modifier uses modified date and time
            SET "dt=%%~tH"
            REM Now split up the date into a usable format.
            REM Change the delims option to the separator your date format uses.
            REM also need a space because the time follows the date 
            FOR /F "tokens=1-3 delims=/. " %%I IN ("!dt!") DO (
                set "dt=%%K%%J%%I"
            )
            IF NOT DEFINED newest IF defined dt set "newest=!dt!" 
            IF DEFINED newest IF defined dt IF !dt! GTR !newest! set "newest=!dt!" 
        )
        POPD
        IF DEFINED newest echo rename "%%~G" "%%G(!newest!)"
    )