This script will get a list of directories (and their subdirectories), loop through each directory to check for subdirectories, then list only the directory names that did not contain a subdirectory. The original script in the link provided works similarly except that it will only list completely empty directories (not containing subdirectories or files). Here is a breakdown of each section of code:
The for /d
in your example is getting a recursive list of directories:
for /d /r %1 %%A in (.) do ( )
- for /d loops through the specified set of directories
- for /d /r tells the
for
loop to recurse into subdirectories
- %1 is an optional file path specified from the command-line
- %%A will return the current directory in each loop
- in (SET) specifies the directory set to loop through
- Specifying "in (.)" tells
for
to loop through all directories
The code inside your for
loop then checks each directory to see if it's empty*:
dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
- dir /ad /b "PATH" gets a list of subdirectories in the specified path*
- "%%~fA" expands the current directory name to its full path
- 2>nul hides any
dir
errors by redirecting STDERR to nul
- | pipes the list of subdirectories found by
dir
into findstr
- findstr "^" then checks for a non-empty list of subdirectories
- >nul hides the
findstr
results by redirecting all output to nul
- || runs a command if the previous command failed (no
findstr
results)
- echo %%~fA returns the directory name if no sub-directories were found*
*Please Note: as mentioned by LotPings, the code you provided will produce different results than in the example you linked to. dir /a /b
lists all files and directories while dir /ad /b
lists directories only. This means that your script will list all directories not containing a subdirectory (but that may still contain files). If this was the expected behavior, please disregard this note.
Edit: further broke down the above list of commands as suggested by Ben Voigt.