Delete objects which are older than X days automatically

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.

  1. Task Scheduler > Create Task
  2. Name it your job. Mine is DeleteOldBackupsOlderthan30days
  3. Click on Run whether the user is logged on or not
  4. Click on the Triggers tab then click on the New… button.
  5. In Begin the task section I will choose the on a schedule option.
  6. 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.
  7. Recur every section and left it to default as 1.
  8. In the Advance settings section check the box Enabled, and click OK to close the Trigger options.
  9. Click on the Actions tab then click on the New… button.
  10. In the Actions section, choose Start a program.
  11. 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.
  12. 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

Published by Hasan Altin

I don't see any difference between the one who doesn't share its knowledge or the one who doesn't share its bread.

Leave a Reply

Your email address will not be published. Required fields are marked *