Finding Old Files

by Nov 20, 2008

Occasionally, you might want to find files that are older than a give number of days to delete or backup those. A simple filter can provide that functionality:

filter FileAge($days) { if ( ($_.CreationTime -le (Get-Date).AddDays($days * -1) )) { $_ } }

Pipe the result of a Dir into FileAge filter, and it will only let those files pass that are at least the specified number of days old. The following line finds all PowerShell Script files in your personal folder that are at least 10 days old:

Dir $home*.ps1 | FileAge 10

You could easily delete or backup the resulting files like this:

Dir $home*.ps1 | FileAge 10 | Del -WhatIf