Active Directory Timestamp Conversion through PowerShell

At this point I’ve become a complete convert to Active Directory administration through PowerShell 2.0 and the Active Directory Module.  Granted, there are some tasks which just make more sense to execute through the GUI, but most of the time I find that PowerShell is a superior interface. Here’s a link for anyone who isn’t familiar with it:

There was one thing that really used to bother me about it, though, and that was the timestamps.  Let’s say I do a lookup on my account:

PS C:\tools\powershell> $user = get-aduser bsweeney -properties lastlogontimestamp

PS C:\tools\powershell> $user

DistinguishedName : CN=bsweeney,OU=testusers,DC=sweeneyops,DC=lab
Enabled : True
GivenName : bsweeney
lastlogontimestamp : 129833580060255031
Name : bsweeney
ObjectClass : user
ObjectGUID  : 7fbf1e01-6a59-42d6-9321-787e145dae06
SamAccountName : bsweeney
SID : S-1-5-21-374116659-2851274-313409940-46522
Surname            :
UserPrincipalName  : bsweeney@sweeneyops.lab

As you can see, the lastlogontimestamp is unintelligible.  There’s no point in outing it to a spreadsheet or trying to determine something from it.  The only option is to convert it. 

As it turns out, its actually very easy to convert.  I just didn’t know how to at the time.  Now I do, and I’m sharing with you, cuz that’s just the kind of guy I am.  The trick is to use the FromFileTime method of then datetime .NET object , which you can see in this block of code:


Where $mydatetime = $user.lastlogontimestamp

So expanding on the sample above:

PS C:\tools\powershell> $mydatetime = $user.lastlogontimestamp
PS C:\tools\powershell> $time = [datetime]::FromFileTime($mydatetime)
PS C:\tools\powershell> $time

Tuesday, June 05, 2012 4:20:06 AM

And, of course, you could collapse all that down into a single line of code:

PS C:\tools\powershell> get-aduser bsweeney -properties lastlogontimestamp | [datetime]::FromFileTime($($_.lastlogontimestamp))

Tuesday, June 05, 2012 4:20:06 AM

Pretty cool, eh?! And at this point we can now convert any timestamp in AD to a human readable format in our scripts.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: