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

Jerold Schulman

March 6, 2002

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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.

Examples:

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


Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like