ATE

How do I use a PowerShell filter to identify files by date?

Asking how to use a Windows PowerShell filter to find objects by date is a pretty common request from IT administrators. It often comes in the form of, "I need to identify all files older than a certain date."

The first step is to establish your date:

$date = (Get-Date).AddDays(-90)

This gets the current date in a parenthetical command. The resulting date object has an AddDays() method, and adding a negative 90 days gives you the date from 90 days ago. This method accounts for leap years, months of varying lengths and all the other variables, so it'll always return an accurate date.

In PowerShell v3, you can then use Get-ChildItem to retrieve a list of files. Use –recurse to include subfolders and then –file (which is a new parameter in v3) to only return files:

Get-ChildItem –Path C:\Logs\ -Recurse –File

These file objects have a variety of date-related properties, including LastAccessTime. Simply filter on that:

Get-ChildItem –Path C:\Logs\ -Recurse –File |
Where-Object

Requires Free Membership to View

–Filter { $PSItem.LastAccessTime –lt $date }

Note that in PowerShell v2, $PSItem must be replaced with $_. You'll also have to compensate for the missing –File parameter in v2:

Get-ChildItem –Path C:\Logs\ -Recurse |
Where-Object –Filter { -Not ($_.PsIsContainer) } |
Where-Object –Filter { $_.LastAccessTime –lt $date }

PsIsContainer is $True for directories and $False for files. Either way, the output of these commands will be files whose LastAccessTime is less than (older than) 90 days ago. You can then do whatever you want with them.

About the author
Don Jones is a well-known and respected PowerShell expert and educator. He's co-author of three books on PowerShell (see PowerShellBooks.com for a list). You can find his content online, including his PowerShell Q&A forums, by visiting DonJones.com.

This was first published in February 2013

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: