The task to output only the directories not containing any subdirectory in a directory of which path is passed to the batch file as first argument string can be done with a batch file with just the following single command line:
@if not "%~1" == "" for /D %%I in ("%~1\*") do @dir "%%I" /AD /B | %SystemRoot%\System32\findstr.exe /R "." >nul || echo %%I
@
at beginning of the command line disables output of the entire command line after parsing it by cmd.exe
before executing it.
The IF condition checks if the batch file was started with at least one non-empty argument string. There is done nothing if the batch file is started without any argument string like on double clicking on it in Windows File Explorer or on running it with just ""
as first argument string.
The for /D
loop searches in the directory of which path was passed to the batch file for any subdirectory. Each found subdirectory is assigned with path to the specified loop variable I
before executing the command line.
@
left to command dir
prevents the output of the command line executed several times by FOR depending on number of subdirectories found in the specified directory.
There is run for each subdirectory in specified directory the command DIR to output in bare format because of option /B
just file system entries with the directory attribute because of option /AD
, i.e. a list of subdirectories in the directory of which path is assigned currently to the loop variable I
.
A directory has always two subdirectories: .
and ..
DIR exits for that reason always with exit code 0 for success even if there are no real subdirectories. This is the reason for redirecting with |
the output of DIR to input of FINDSTR which searches on all lines output by DIR with a regular expression for any character.
The output of FINDSTR on finding any line with a least one character is of no interest and is redirected for that reason to device NUL to suppress it. There is only of interest the exit code of FINDSTR which is either 0
on DIR output any directory name or 1
on DIR output nothing and so FINDSTR could not find any character.
There is executed the command ECHO to output the directory path assigned currently to the loop variable I
if DIR could not find any subdirectory in this directory with the exception of .
and ..
not output because of using bare output format. Please see single line with multiple commands using Windows batch file for an explanation of conditional command operator ||
.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
... explains %~1
... first argument string with surrounding "
removed
dir /?
echo /?
findstr /?
for /?
if /?