Performing an operation in each subdirectory of a directory tree from batch

Raymond Chen

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.)

The /F option enables various special behaviors of the FOR command. 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 usebackq option, but I’m not using that here.) Therefore, the FOR command will run the dir /ad/s/b command and parse the output. The 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 %i variable. (Normally, only the first word is assigned to %i.) Therefore, the FOR loop executes once for each subdirectory, with the %i variable set to the subdirectory name.

The command request to be performed for each line is simply echoing the directory name. 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"

Nitpicker's corner

I doubt anybody actually enjoys working with batch files, but that doesn't mean tips on using it more effectively aren't valid.

0 comments

Discussion is closed.

Feedback usabilla icon