fbpx Find All Files Modified Before a Certain Date | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Find All Files Modified Before a Certain Date

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. 

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say