<< Latest Post

Monday, April 08, 2013

Ms-DOS For Loop

After a long time, I used good old Ms-DOS to recursively delete large number of directories (~2500+) in Windows. A simple for loop like below is useful to do the same, 

To list the directories -
FOR /F "delims=" %i IN ('dir /s /b /ad <directory name>') DO @echo "%i"

To delete the directories -
FOR /F "delims=" %i IN ('dir /s /b /ad <directory name>') DO rmdir /S /Q "%i"


/F - Option to process the output of a command or file list. If it is not mentioned, then the whole section after "IN" with the "dir" command will be treated as a string.

delims= - Delimiter character. The default value is space & tab. Note - If not overridden as above or never mentioned in the command, the output gets chopped at the space if a directory name has any spaces. In the above scenario, the delimiter will be the end of line.

dir - Directory listing command with options,

  • /s - Display files in the specified directory & sub-directories
  • /b - Bare bones listing without time-stamp, volume or file size info.
  • /a - Display files with specified attributes. In this case,
    • d - to display directories only.

For more detailed Information on For loop can, check out this link