JSI Tip 4934. How do I execute a command in every sub-folder?

The FOR /R command is meant to traverse sub-folders.

The general syntax is:

FOR /R \[\[drive:\]path\] %variable IN (set) DO command \[command-parameters\]

Walks the directory tree rooted at \[drive:\]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.


To delete every *.log file in all the folders of your profile, type:

for /r "%userprofile%" %i in (*.log) do del /q "%i"

NOTE: If used in a batch file, the %variable must be %%variable.

To list all the sub-folders of your profile, type:

for /r "%userprofile%" %i in (.) do @echo %i

To list every sub-folder of the current directory, type:

for /r %i in (.) do @echo %i

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.