Link to home
Start Free TrialLog in
Avatar of MBUNITED
MBUNITED

asked on

How to delete folders recursively in DOS

Hi,

I have a folder named Test with sub directorties. I'd like to be able to create a simple batch file that deletes all folders within test and test's sub directories that match a supplied name. I know how to create the batch command but im not sure how i can create the recursive delete using a DOS command.

i.e if i want to delete any folder with the name "garbage"  with in the folder test and its sub directories is there a command I can issue such as

rmdir c:\test\ "garbage" -s - q

that will delete all folders with test including any folder named "garbage" within the folder test recursively.

Thanks,
Avatar of knightEknight
knightEknight
Flag of United States of America image


c:
cd c:\test
for /f %%D in ('dir/s/b/ad ^| find/i "garbage" ') do @echo rd/s/q %%D
 
I left in the @echo clause just so you can see what it will do before actually doing it.  You will therefore need to remove the @echo in order for it to actually remove the garbage folders.
Avatar of flyingsky
flyingsky

rmdir /s <directory name>
Avatar of MBUNITED

ASKER

Hi knightEknight,

Whats the actual commad i need to put in the batch file is it

cd c:\test
for /f %%D in ('dir/s/b/ad ^| find/i "garbage" ') do rd/s/q %%D

Im currently getting the error message
%%D was unexpected at this time.
In a batch file you must use two percent (%) symbols as you have shown above.
On a command prompt (e.g. not in a batch file) you must use only one, e.g.   for /f %D in ...

so yes, in a batch file, the command you posted looks correct.  I'm re-posting to add surrounding quotes, and an IF clause to check for the directories existence, since the parent directories may be removed before the children:

c:
cd c:\test
for /f %%D in ('dir/s/b/ad ^| find/i "garbage" ') do if exist "%%D" rd/s/q "%%D"
ASKER CERTIFIED SOLUTION
Avatar of knightEknight
knightEknight
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks knightEknight that worked