Wednesday, August 17, 2016

Delete Files Older than X Days and Delete Empty Folders

(1) Create a new text document (Del_OldDocs.txt)
(2) copy the script

REM Remove files older than X Days
forfiles -p "D:\Dir1\OldFolders" -s -m *.* /D -7 /C "cmd /c del @path"

cd /D    D:\Dir1\OldFolders
for /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d">NUL

(3) save the text document as Del_OldDocs.bat
(4) Run the script
(5) You can also run the script as job in the Task Scheduler


Note:
Please do some testing before using it in Production

D:\Dir1\OldFolders   -- this is the path where you have your old folders to be deleted
X Days -- Replace X with days (7 is used for one week), replace 7 with the number of days you want

First part of the script removes all the files in the OldFolders directory and Empty Folders still remain
Second part of the script will remove all the Empty Folders within OldFolders directory