Filtering Based On File Age

by Dec 26, 2008

Every so often, you'll need to filter files by age. Maybe you'll only want to see files that are older than 20 days old and delete them or back them up. So, you need a way to filter file age relative to the current date. Here is a custom filter that just does this:

Filter Select-FileAge {
param($days)
# is it a folder? Then omit:
If ($_.PSisContainer) {
# do not return folders effectively filtering them out
} ElseIf ($_.LastWriteTime -lt (Get-Date).AddDays($days * -1)) {
$_
}
}

With this filter, the next line gets you all log files in the Windows folder that weren't modified within the past 20 days.

dir $env:windir *.log | Select-FileAge 20

If you'd like to base your filter on the creation time, rather than the modification time, change LastWriteTime to CreationTime in your filter.

Or, you can make your filter even more flexible by allowing a user to specify interactively which property to use for filtering:

filter Select-FileAge {
param($days, $property = 'LastWriteTime')
if ($_.$property -lt (Get-Date).AddDays($days * -1)) {
$_
}
}

If the user does not specify a second parameter, it defaults to LastWriteTime. To filter based on CreationTime, use it like this:

Dir $home | Select-FileAge 30 'CreationTime'

Can you make the comparison dynamic, too? Yes, for example try this:

filter Select-FileAge {
param($days, $property = 'LastWriteTime', $operator = '-lt')
$condition = Invoke-Expression("`$_.$property $operator (Get-Date).AddDays($days * -1)")
if ($condition) {
$_
}
}

The following line retrieves all files that where created in the past 10 days in your user profile folder. You can specify the age, the property to compare and the comparison operator.

dir $home | Select-FileAge 10 'CreationTime' '-ge'