Following our script series, we will explain in this tutorial the way to create a script to delete files older than 7 days. Will perform this operation using forfiles to delete files. 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 provides a 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 the command line.
- Batch to zip files – Script to zip files using cmd command.
Delete older than 7 days.
We will explain two methods:
- Batch script to remove files older than based on the extension of the file.
- Batch to delete all files.
Batch to delete files older than based on the extension.
In this example, we will configure the 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 your needs.
Also, you can READ:
- Batch to delete folder – Delete folder using 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 don’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 Script to delete all files oldr 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 delete.
You can schedule with Task Scheduler. Read this.
If you have any questions feel free to ask in the comment section.
Please rate use if this article was helpful to you!
—————————————————————————————————