How to best delete directories

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
OM3
Posts: 32
Joined: 17 Mar 2014 08:43

How to best delete directories

#1 Post by OM3 » 25 Jan 2015 23:51

I've found a code snippet to delete files older than 30 days
How do I change so that I do the same for folders instead of files?

So, what I want is: delete folder AND its contents if the folder is older than 30 days

The code for deleting the files is:

Code: Select all

REM Remove files older than 30 days
forfiles /p "C:\Users\YOURUSERNAME\Downloads" /s /m *.* /c "cmd /c Del @path" /d -30


After having this setup, I can use Task Scheduler to run this batch file every 30 days
Awesome - just what I wanted

Or is there a better way to do?

Thanks


OM

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: How to best delete directories

#2 Post by Squashman » 26 Jan 2015 07:18

Forfiles has an option to test if the the data is a directory.

ShadowThief
Expert
Posts: 1167
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: How to best delete directories

#3 Post by ShadowThief » 26 Jan 2015 08:01

del can't delete folders

Try using rd /s @path instead.

OM3
Posts: 32
Joined: 17 Mar 2014 08:43

Re: How to best delete directories

#4 Post by OM3 » 27 Jan 2015 08:33

thanks for the replies guys
rd - that only removes empty directories surely?

the only thing i can think of is deltree - but, i'd rather not delete permanently

surely there must be a better option than to: test if directory, then delete files contained, and then remove the directory?

thanks

ShadowThief
Expert
Posts: 1167
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: How to best delete directories

#5 Post by ShadowThief » 27 Jan 2015 08:55

rd by itself just removes directories

the /s flag deletes all files and subfolders as well

From rd /?

Code: Select all

RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path

    /S      Removes all directories and files in the specified directory
            in addition to the directory itself.  Used to remove a directory
            tree.

    /Q      Quiet mode, do not ask if ok to remove a directory tree with /S

OM3
Posts: 32
Joined: 17 Mar 2014 08:43

Re: How to best delete directories

#6 Post by OM3 » 28 Jan 2015 17:44

thanks for the replies guys
for some reason i thought rd only removed empty directories

so... is this correct:

Code: Select all

REM Remove files older than 30 days
forfiles /p "C:\Users\YOURUSERNAME\Downloads" /s /m *.* /c "cmd /c rd /s @path" /d -30


What is /s /sm for?
What does the /c do?
forfiles - do I want this if I want to work on directories?
is there an equivalent for directories?

Thanks!


Post Reply