#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
Share on:
comments powered by Disqus