Windows – How to iterate over directories in the Windows command prompt

command linewindows 7

The Windows command prompt (cmd.exe) provides the FOR command. It can be used to do an operation for any file in a directory. Example:

\> dir
28.05.2012  18:25                69 buildall.bat
28.05.2012  07:48    <DIR>          include
28.05.2012  18:23    <DIR>          sub-607

\> for %d in (*.bat) echo %d

How can I do the same thing (non-recursively) with all subdirectories in a given directory? The idea is:

for %d in (sub-*) do (
  cd %d
  dosomething
  cd ..
)

The for statement above does not find sub-607 becauses it's not a file.

Best Answer

The for command can take the /D switch to iterate over subdirectories, rather than files.

for /D %d in (sub-*) do ...

See here for more information: http://ss64.com/nt/for_d.html