27

How can i get newest subfolder in directory ?
I need it in MKLINK /D command.

Thanks

1

2 Answers 2

64
FOR /F "delims=" %%i IN ('dir /b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%

(%i for windows 10)

  • /b is for bare format
  • /ad-h only directories, but not the hidden ones
  • t:c means to use the creation date for sorting (use t:w for last write date)
  • /od sort oldest first
  • The for /F executes the command and sets a to the directory name, the last one is the newest one.

If you execute this directly on the command line (not in a batch file), use % instead of %%.

This works with the current directory - as @iesou pointed out you'll need to add the directory path after dir if you need to use any other directory path.

Example with specified directory path:

FOR /F "delims=" %%i IN ('dir "c:\Program Files" /b /ad-h /t:c /od') DO SET a=%%i

To prevent going through all subfolders, you may change the sort order to have the most recent first (/o-d) and exit the for loop after the first call:

@echo off
FOR /F "delims=" %%i IN ('dir /b /ad-h /t:c /o-d') DO (
    SET a=%%i
    GOTO :found
)
echo No subfolder found
goto :eof
:found
echo Most recent subfolder: %a%
4
  • 4
    +1 To clarify after the dir and before the /b you need to enter the root directory. Also you don't need the echo if it is part of a batch. You can simply use the %a% variable because the last value it was set to is the newest directory.
    – iesou
    Commented May 9, 2012 at 20:46
  • 1
    @iesou That's correct - if you don't specify the directory, the current directory is used. Added it to the answer, and provided a slightly modified version.
    – marapet
    Commented May 9, 2012 at 21:40
  • @marapet I have used the above script however if the folder has a space in it, it does not work, have I missed something?
    – Arthor
    Commented Jun 23, 2014 at 15:56
  • 1
    @Arthor You are correct, the for command uses default options. You may change FOR /F %%i into FOR /F "delims=" %%i to prevent splitting up the directory name.
    – marapet
    Commented Jun 24, 2014 at 6:48
6

Some improvement for dir names with spaces

FOR /F " tokens=*" %%i IN ('dir /b /ad-h /od') DO (SET a=%%i)  

now you get a=Application Data instead of a=Application
Note: Pay attention to the space in front of "tokens"

1
  • Another improvement to ignore some matches: DO if not "%%i"==".." if not "%%i"=="." SET
    – Thomas
    Commented Dec 2, 2015 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.