batch-file For Loops in Batch Files Recursively Visit Directories in a Directory Tree


for /r command can be used to recursively visit all the directories in a directory tree and perform a command.

@echo off
rem start at the top of the tree to visit and loop though each directory
for /r %%a in (.) do (
  rem enter the directory
  pushd %%a
  echo In directory:
  rem leave the directory


  • for /r - Loop through files (Recurse subfolders).
  • pushd - Change the current directory/folder and store the previous folder/path for use by the POPD command.
  • popd - Change directory back to the path/folder most recently stored by the PUSHD command.