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. It’s very easy to calculate date and time math with Windows PowerShell. The .NET Framework includes two data structures that you can use for calculating all sorts of date math – DateTime and TimeSpan.

90 days before today:

Thursday, August 26, 2010 5:53:39 PM

90 days after today:

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:

Wednesday, November 24, 2010 5:32:18 PM

37 minutes from now:

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:


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: