Thursday, September 13, 2012

Windows Batch File To Delete Specified Files & Folders


To delete files and folders in G:\Test open notepad and copy the following command. Please take note that modify the path and date according to your requirement.

This following line will delete all files (*.*) in G:\Test that are older (created, modified) than 7 days. This will delete only the files from your location.

forfiles -p "G:\Test" -s -m *.* -d "-7" -c "cmd /c del @file"
where -
:/p Path      The Path to search  (default=current folder)
:/s Recurse into sub-folders
:/m Mask
:/D date      Select files with a last modified date greater than or equal to (+), or less than or equal to (-), the specified date using the "dd/MM/yyyy" format;
Note that, this only delete files not folders.

Save the file and rename it into something like Del.bat. Make sure the extension is bat not txt.

To remove empty folders as well you have to use the following line. To remove empty folders in G:\Test, this command should be executed from inside G:\Test.

for /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"

:/ad means select files whose attributes include the Directory attribute (in other words, folders)
:/b switch means give a "bare" listing - just the filenam
:/s means look in subfolders (which, incidentally, modifies /B, so it shows the full pathname)
:/r means sort in reverse order
dir - show file, directory command
rd - Remove directory command

To delete both files and folders copy both of the above line, save as a batch file and execute the file from your inside your specified location. In my case G:\Test.
You can schedule the file so that is will check regularly to delete contents using Windows Task Scheduler.

To know how to use task scheduler you can visit the following pages.
Windows XP 1 2
Windows 7 1 2

No comments:

Post a Comment