Problem
You want to find all files last modified before a certain date.
Solution
To find all files modified before a certain date, use the GetChildItem cmdlet to list the files in a directory, and then use the WhereObject cmdlet to compare the LastWriteTime property to the date you are interested in. For example, to find all files created before this year:
GetChildItem Recurse | WhereObject { $_.LastWriteTime lt "01/01/2007" }
Discussion
Acommon reason to compare files against a certain date is to find recently modified (or not recently modified) files. This looks almost the same as the example given by the solution, but your script can’t know the exact date to compare against.
In this case, the AddDays() method in the .NET Framework’s DateTime class gives you a way to perform some simple calendar arithmetic. If you have a DateTime object, you can add or subtract time from it to represent a different date altogether. For example, to find all files modified in the last 30 days:
$compareDate = (GetDate).AddDays(30) GetChildItem Recurse | WhereObject { $_.LastWriteTime ge $compareDate }
Similarly, to find all files more than 30 days old:
$compareDate = (GetDate).AddDays(30)
GetChildItem Recurse | WhereObject { $_.LastWriteTime lt $compareDate } In this example, the GetDate cmdlet returns an object that represents the current date and time. You call the AddDays() method to subtract 30 days from that time, which stores the date representing “30 days ago” in the $compareDate variable. Next, you compare that date against the LastWriteTime property of each file that the GetChildItem cmdlet returns.
The DateTime class is the administrator’s favorite calendar!
PS >[DateTime]::IsLeapYear(2008)
True
PS >$daysTillSummer = [DateTime] "06/21/2008" (GetDate)
PS >$daysTillSummer.Days
283
For more information about the GetChildItem cmdlet, type GetHelp GetChildItem.