Sometimes you need to remove objects which are older than X days. I will share a good tip that let you remove your old files automatically. For instance, if your disk is getting full because of some log files or backups for some reason this tip saves your space on the hard drive. We are going to use Windows Task Scheduler and create a new job and set it to run automatically due to your environment.
Follow the instruction, and I will point you exactly what to do.
- Task Scheduler > Create Task
- Name it your job. Mine is DeleteOldBackupsOlderthan30days
- Click on Run whether the user is logged on or not
- Click on the Triggers tab then click on the New… button.
- In Begin the task section I will choose the on a schedule option.
- In the Settings section, On the left side, choose Daily, and on the right side select the date and time that you want your jobs to run automatically.
- Recur every section and left it to default as 1.
- In the Advance settings section check the box Enabled, and click OK to close the Trigger options.
- Click on the Actions tab then click on the New… button.
- In the Actions section, choose Start a program.
- In the Settings section, there are three fields, in the program/script field, just type powershell.exe or use the browse button to find the PowerShell.exe in the C:\Windows\System32\WindowsPowerShell\v1.0 path.
- Modify the following command and copy then paste it into the field of Add arguments (optional) section. Do not forget to replace the path and the day. In this example, 30 days old objects in the path will be deleted automatically. After you set the path and the day, click OK to close the Actions settings.
Get-ChildItem –Path "D:\Data\Backups" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item
The last thing is to click on the OK button at the bottom of the window and enter the username and password which has privileges to run this scheduled job.
Thanks for your time reading my article about deleting objects automatically. Have a good and successful day.
Hasan Altin