4
Nov/09
2

Recursively delete Subdirectories from a command prompt

Some might have noticed that the “del” command will only remove files in a directory and it’s subdirectories.
If you want to delete Subdirectories from a given starting directory (without deleting the root directory itself) you might want to parse through the root folder and delete every directory that is found.

Here’s a small for loop which does the trick.

In this example, all folders within the %temp% folder that start with “OL” would be deleted (Since that is what the “dir” command would return). You might want to modify the path and the wild card to suit your requirements.

In a command line:
for /f %i in ('dir %temp%\OL* /B /D') do rd %i /Q /S
In a batch file:
for /f %%i in ('dir %temp%\OL* /B /D') do rd %%i /Q /S

Print This Post
(No Ratings Yet)
Loading ... Loading ...
1,915 views
Comments (2) Trackbacks (0)
  1. If you want to delete ALL subdirectories regardless of their name, I found it better to use the directory switch. The above script couldn’t handle some of the longer name directories I wanted removed.

    So this is what I would use to delete *ALL* subdirectories in %temp% (notice I use “” around the output as a precaution to catch long folder names that may contain spaces and strange characters)

    In a command line:
    for /d %i in (%temp%\*) do rd “%i” /Q /S
    In a batch file:
    for /d %%i in (%temp%\*) do rd “%%i” /Q /S

    If you want to be more specific about the folders you are deleting you can do the same as the original script and delete the folders you want to filter starting with whatever letter or word you choose.

    E.g. — Where “OL” is the starting letters of the directories you wish to filter out.
    In a command line:
    for /d %i in (%temp%\OL*) do rd “%i” /Q /S
    In a batch file:
    for /d %%i in (%temp%\OL*) do rd “%%i” /Q /S

  2. Thanks LJ! I always start with “for /f” and forget about the /d switch. You’re absolutely right.

Leave a comment


No trackbacks yet.