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:
[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
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()