How to periodically delete files older than a certain time in Windows?

2

1

I want to make a scheduled process in Windows (specifically, Windows 7) that every 3 hours will delete all the files in all folders older than 24 hours (like the Unix find's -mtime +1). Basically the Windows equivalent of having this configured in my Unix cron:

find $TRANSITDIR -mtime +1 -exec rm -rf {} \;

Although I seem to have found that the Windows cron equivalent is the scheduler, I just don't know the Windows commands to do that.

Does anyone have a scheduler script ready-to-go?

flpgdt

Posted 2011-07-29T14:52:02.300

Reputation: 457

Related: http://superuser.com/q/434626/108226. The solution I posted (using PowerShell) can be fairly easily modified to work on any folder or drive, not just the recycle bin, and can be scheduled using the Task Scheduler GUI or the command-line schtasks.exe.

– Indrek – 2012-11-05T21:28:14.983

Answers

1

Create a batch file with the following contents:

REM Remove files older than 1 day
forfiles /p %1 /s /m * /c "cmd /c del @path /q" /d -1

Then open Windows Task Scheduler. Create a basic task to run a program, and as the argument give the path to the folder in quotes.

Explanation of commands

REM is a comment.

forfiles will run a command for each file. /p %1 defines what path the files are in (%1 means the value of the first command line argument passed to the script). /s is recursive (goes into subfolders). /m *.* is the file name mask. /c "cmd /c del @path" specified what command to execute. /d -1 means files older than 1 day.

In this case, cmd /c del @pat /qh creates a new session and runs del (delete file) on @path, the file path for each file iterated over by forfiles. /q is for quiet mode, so that it doesn't ask you to confirm for directories.

Testing

Replace del with echo. This will print each file that would have been deleted, instead of actually deleting it.

Superbest

Posted 2011-07-29T14:52:02.300

Reputation: 1 739

0

Not exactly what you want to do, but I'd say that the automatic clearings of ccleaner are worth to take in consideration when talking about windows. I use it to find and clean tmp files for windows machines.

It has a limited CLI http://www.piriform.com/docs/ccleaner/advanced-usage/command-line-parameters#Command-line_parameters_for_CCleaner_

Also provided that you're a shell guy and you said you need it for W7, you can try powershell:

http://www.google.es/search?q=powershell+remove+x+day+older+files

hmontoliu

Posted 2011-07-29T14:52:02.300

Reputation: 427