#PSTip Get old files based on LastWriteTime

Note: This tip requires PowerShell 2.0 and above

There are many ways to get the age of a file. The most common way is to subtract the file’s LastWriteTime from the current time:

PS> $now = Get-Date
PS> $prof = Get-ChildItem $PROFILE
PS> ($now - $prof.LastWriteTime).Days

Or by using the Subtract method:

PS> $now.Subtract($prof.LastWriteTime).Days

There is another way to get the information using a  less known method of piping a file system object to the New-TimeSpan cmdlet:

PS> ($prof | New-TimeSpan).Days

The Start parameter of the New-TimeSpan cmdlet has a LastWriteTime parameter Alias which automatically bind the value of the incoming file system object

PS> (Get-Command New-TimeSpan).Parameters.Start

Name            : Start
ParameterType   : System.DateTime
ParameterSets   : {[Date, System.Management.Automation.ParameterSetMetadata]}
IsDynamic       : False
Aliases         : {LastWriteTime}
Attributes      : {System.Management.Automation.AliasAttribute, Date}
SwitchParameter : False

Here’s an example of all DLL file’s age in PowerShell’s installation directory

PS> $age = @{Name='Age(Days)'; Expression={($_ | New-TimeSpan ).Days }}
PS> Get-ChildItem $PSHOME -Filter *.dll | Select-Object Name,$age

Name                  Age(Days)
----                  ---------
PSEvents.dll                 68
pspluginwkr-v3.dll           68
pspluginwkr.dll             121
pwrshmsg.dll                 68
pwrshsip.dll                 68

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: