Delete files x days out or older PDF Print E-mail
Written by Tim Andaya   
Tuesday, 20 May 2014 08:36

Often times processes that we create for our customers generate files that are then manipulated by other programs and later become so much garbage orphaned in directories. The process below can help with clean up.

NOTE:  extensive testing before implementation is strongly advised.

Here are two techniques you can use depending on your shell preference, cmd or PowerShell.

Using the CMD line (batchable)

  1. forfiles -p ":\" -s -m *.* -d -5 -c "cmd /c echo @file"
    (This will print the selection to screen)
  2. forfiles -p "":\" " -s -m *.* -d -5 -c "cmd /c del @path"
    (This will delete the files in the directory that are older than five days from the current date.

Using Powershell (scriptable)

  1. Get-ChildItem –Path “:\” –Recurse | Where-Object CreationTime –lt (Get-Date).AddDays(-5) | Remove-Item
    (Powershell 3)
  2. Get-ChildItem –Path “:\” –Recurse | Where-Object{$_.CreationTime –lt (Get-Date).AddDays(-5)} | Remove-Item
    (Powershell 2)
  • First we get FileInfo and DirectoryInfo objects in the Path :\.
  • FileInfo and DirectoryInfo objects both contain a CreationTime property, so we can filter the collection using that.
  • The –lt (less than) operator is then used to compare the CreationTime property of the objects with Get-Date (the current date) subtract 5 days.
  • This then leaves us with a collection of objects that were created more than 5 days ago, which we pass to Remove-Item.

Tip: To see what will be removed you can use the –WhatIf parameter:

Get-ChildItem –Path “:\” –Recurse | Where-Object CreationTime –lt (Get-Date).AddDays(-5) | Remove-Item –WhatIf