Performing an operation in each subdirectory of a directory tree from batch
To execute a command in each subdirectory of a directory tree
from a batch file, you can adapt the following:
for /f "delims=" %%i in ('dir /ad/s/b') do echo %%i
(If you want to play with this command from the command prompt,
then undouble the percent signs.)
/F option enables various special behaviors
The most important change is that a string in single-quotation marks
causes the contents to be interpreted as a command whose output is
to be parsed.
(This behavior changes if you use the
but I’m not using that here.)
FOR command will run the
dir /ad/s/b command and parse the output.
dir /ad/s/b command performs a recursive listing
of only directories, printing just the names of the directories found.
The option we provide,
delims= changes the default
delimiter from a space to nothing.
This means that the entire line is to be read into the
(Normally, only the first word is assigned to
FOR loop executes once for each subdirectory,
%i variable set to the subdirectory name.
The command request to be performed for each line is simply echoing the
In real life, you would probably put something more interesting here.
For example, to dump the security descriptor of each
directory (which was the original problem that inspired this entry),
you can type this on the command line:
for /f "delims=" %i in ('dir /ad/s/b') do cacls "%i" >>"%TEMP%\cacls.log"
I doubt anybody actually enjoys working with batch files,
but that doesn't mean tips on using it more effectively aren't valid.