How to Use the FOR /D Loop to Iterate Through Folders in Batch Script
When you need to automate tasks across multiple directories (such as cleaning up temporary files in every user's profile or running a build command in several project folders) you need a way to loop through them. While the standard FOR loop is for files, batch scripting provides a specific switch, /D, to create a loop that iterates exclusively through Directories.
This guide will teach you how to use the FOR /D command to process subdirectories in a given path. You will learn the correct syntax, how to use wildcards to filter your selection, and understand its non-recursive limitation, which will lead us to the FOR /R command for processing entire directory trees.
The Core Command: FOR /D
The FOR /D command is a special variant of the FOR loop designed to iterate over a set of directories. It will not see or process any files.
The Syntax: FOR /D %%V IN (Set) DO command
/D: The switch that specifies directory iteration.%%V: The loop variable that will hold the name of each directory found.(Set): A set of directories to iterate through, almost always specified with a wildcard (e.g.,*).command: The command to execute for each directory.
Basic Example: Listing Immediate Subdirectories
Let's use FOR /D to list all the subdirectories in the C:\Windows folder.
@ECHO OFF
ECHO --- Subdirectories in C:\Windows ---
ECHO.
REM The (*) is a wildcard that matches all directories in the specified path.
FOR /D %%D IN ("C:\Windows\*") DO (
ECHO Found directory: "%%D"
)
In Output (truncated), the loop finds each subdirectory and the %%D variable holds its full path.
--- Subdirectories in C:\Windows ---
Found directory: "C:\Windows\addins"
Found directory: "C:\Windows\appcompat"
Found directory: "C:\Windows\apppatch"
...
Found directory: "C:\Windows\System32"
Using Wildcards to Filter Folders
The Set part of the command can use wildcards to filter which directories are processed.
This script only loops through directories in C:\Users that start with the letter "A".
@ECHO OFF
FOR /D %%U IN ("C:\Users\A*") DO (
ECHO Found user folder starting with 'A': "%%~nxU"
)
Output (example)
Found user folder starting with 'A': "Admin"
Found user folder starting with 'A': "All Users"
%%~nxU is used to get just the name and extension (folder name) part of the path.
The Recursive Alternative: FOR /R
A critical limitation of FOR /D is that it is not recursive. It only looks at the immediate subdirectories of the path you specify and will not go deeper into the directory tree.
To process a folder and all subfolders beneath it, you must use the FOR /R (Recursive) command.
Pattern: FOR /R "StartPath" %%D IN (.) DO command
/R "StartPath": Specifies the root folder to start the recursive walk.IN (.): This is a trick. The.represents the current directory. This tells theFOR /Rloop to operate on each directory it finds during its walk.
This script will find every single subdirectory, at every level, inside C:\MyProject.
@ECHO OFF
ECHO --- All subdirectories in C:\MyProject ---
FOR /R "C:\MyProject" %%D IN (.) DO (
ECHO Found folder: "%%D"
)
Common Pitfalls and How to Solve Them
Problem: The Path Contains Spaces
If the path you are searching in contains spaces, the command will fail unless it is properly quoted.
Solution: Quote the Path and the Variable
This is a universal best practice.
REM Correctly quoted path in the set
FOR /D %%F IN ("C:\Program Files\*") DO (
REM Correctly quoted loop variable for use in a command
ECHO "%%F"
)
Problem: Hidden Folders are Not Included
The FOR /D command will not see hidden directories. This can lead to an incomplete or incorrect result if you are trying to perform a comprehensive cleanup or search.
The Solution: Use DIR with FOR /F
The most robust way to find all directories, including hidden ones, is to use the DIR command with the appropriate attribute switches and process its output with a FOR /F loop.
REM /ADH lists directories, including hidden ones. /B gives bare format.
FOR /F "delims=" %%D IN ('DIR /ADH /B "C:\SomePath"') DO (
ECHO Found directory (including hidden): "%%D"
)
For any script that requires absolute completeness, this DIR-based method is superior to FOR /D.
Practical Example: A Batch "Build" Script
This script simulates a build process. It looks for all subfolders in a C:\Projects directory and, for each one it finds, it navigates into that folder and runs a build.bat script if one exists.
@ECHO OFF
SETLOCAL
SET "ProjectsRoot=C:\Projects"
ECHO --- Multi-Project Build Runner ---
ECHO.
FOR /D %%P IN ("%ProjectsRoot%\*") DO (
ECHO --- Checking in project: "%%~nxP" ---
REM Use PUSHD to change directory and POPD to return safely.
PUSHD "%%P"
IF EXIST "build.bat" (
ECHO build.bat found. Executing...
CALL build.bat
) ELSE (
ECHO No build.bat found in this project.
)
POPD
ECHO.
)
ECHO --- All projects checked ---
ENDLOCAL
Conclusion
The FOR /D loop is the specialized tool for iterating through directories in a batch script, making it easy to automate tasks across multiple folders.
Key takeaways:
- Use
FOR /Dto loop through the immediate subdirectories of a given path. - Use
FOR /Rwith the(.)set to loop recursively through an entire directory tree. - For scripts that must see hidden folders, the more robust method is to use
DIR /ADH /Bpiped into aFOR /Floop. - Always quote your paths (
"...") to handle spaces and prevent errors.