Date and Time Math with PowerShell

How many times have you had to figure out what date was X days, months, or years ago, or perhaps what time was Y minutes, hours, or seconds ago? Producing a report of all the users who have not logged in during the past 90 days is a pretty common request. There’s two ways to go about doing this – the lazy way and the precise way. The lazy way is to say well 90 days is about three months ago, and it’s 11/24 today so that would be 8/24. The precise way is to realize that 90 days go is actually 8/26. If you’ve got Windows PowerShell on your desktop (Windows 7 includes it out of the box), it’s super easy to calculate these sorts of things. The .NET Framework includes a couple of data structures that you can use for figuring out all sorts of date math – DateTime and TimeSpan.

90 days before today:

[DateTime]::Now.Subtract([TimeSpan]::FromDays(90))
Thursday, August 26, 2010 5:53:39 PM

90 days after today:

[DateTime]::Now.Add([TimeSpan]::FromDays(90))
Tuesday, February 22, 2011 6:03:16 PM

2 years before today:

[DateTime]::Now.Subtract([TimeSpan]::FromDays(2 * 365))
Monday, November 24, 2008 6:06:59 PM

2 years after today:

[DateTime]::Now.Add([TimeSpan]::FromDays(2 * 365))
Friday, November 23, 2012 6:06:51 PM
Note: We’re not taking leap years in to account in the above two examples.

37 minutes ago:

[DateTime]::Now.Subtract([TimeSpan]::FromMinutes(37))
Wednesday, November 24, 2010 5:32:18 PM

37 minutes from now:

[DateTime]::Now.Add([TimeSpan]::FromMinutes(37))
Wednesday, November 24, 2010 6:47:41 PM

Finally, if you’re looking to construct an LDAP filter based on a timestamp attribute (e.g. pwdLastSet, lastLogonTimeStamp, etc.), you can either use adfind (which will do the encoding for you) or you can convert the time you want to filter on to a standard Windows File Time:

[DateTime]::Now.ToFileTime()
129351176175846050

You can use the ToFileTime() method on any of the above expressions, so, if for example you wanted 90 days ago in this format you could do this:

[DateTime]::Now.Subtract([TimeSpan]::FromDays(90)).ToFileTime()

Posted Wednesday, November 24 2010 6:15 PM by | Comments
Tagged as: , ,

Comments