Following our script series we will explain in this tutorial the way to create script to delete files older than 7 days. Will perform this operation using forfiles to delete files older than. If you work with backups you know that doesn’t need backups older than x days. For that you need to delete manually every few days. This script provide solution to automate this process. You can schedule to run automatically and save some time of your work. Worked on most windows platforms.
Also you can READ:
- Batch to delete files – Delete files automatically using command line.
- Batch to zip files – Script to zip files using cmd command.
Delete files older than 7 days.
We will explain two methods:
- Script to delete files older than based on extension of the file.
- Batch to delete all files.
Script to delete files older than based on extension.
In this example we will configure script to delete old files with .bak . Copy the below command and past in text file. Save as delete.bat. Save anywhere except D:\Backup\ .
Echo Forfiles to delete files older than 7 days forfiles -p D:\Backup\ -s -m *.bak* /D -7 /C "cmd /c del /q @path" echo Done!
Explanation of the commands:
D:\Backup\ – Replace with your path.
*.bak* – Replace with your file extension.
-7 – Period to be deleted. Can replace with your needs.
Also you can READ:
- Batch to delete folder – Delete folder usin command line.
- -p – The path to search for the files you want to check the date of and remove.
- -s – Recourse subdirectories contained within the path specified using /p and check them as well. Remove if you doesn’t want to delete files in subdirectories.
- -m – The search mask to be used for the file type you want to check the date on (*.* being all files).
- /d – The date to compare the files. Also can be used (dd/mm/yyyy) a standard date type.
- /c – The command to be used on a file that matches the /m and /d criteria.
- /q – Used within /c to instruct the del command to delete files quietly.
Other Parameters here.
Run as Administrator and files with defined extension will be deleted.
Script to delete all files.
We will configure the script to delete all files older than 7 days.
Echo forfiles delete files older than 7 days forfiles -p D:\Backup\ -s -m *.* /D -7 /C "cmd /c del /q @path" echo Done!
Run as Administrator and files located in the “Backup” folder will deleted.
You can schedule with Task Scheduler . Read this.
If you have any question feel free to ask on the comment section.
Please rate use if this article was helpful to you!