Tuesday, July 8, 2008

One-liner in PowerShell? Convert a 64-bit (Integer8) value to date time

As I was converting my VBScripts to PowerShell, I reviewed one which checks for the password expiration of a user in Active Directory. The blog post I've had sometime last year extracts object properties and one of them is the pwdLastSet property which specifies a 64-bit value of when the user last changed their passwords. This is necessary if you need to know how many days left before their password expires. One of the things I did was to use a function that converts the 64-bit value to a valid date/time value - thanks to Richard Mueller, of course.

Function Integer8Date(ByVal objDate, ByVal lngBias)
' Function to convert Integer8 (64-bit) value to a date, adjusted for
' local time zone bias.
Dim lngAdjust, lngDate, lngHigh,
lngLow
lngAdjust
=
lngBias
lngHigh
=
objDate.HighPart
lngLow
=
objdate.LowPart
' Account for bug in IADslargeInteger property methods.
If (lngLow < 0)
Then
lngHigh = lngHigh +
1
End If

If
(lngHigh = 0) And (lngLow = 0)
Then
lngAdjust =
0
End If

lngDate = #1/1/1601# + (((lngHigh * (2 ^ 32))
_
+ lngLow) / 600000000 - lngAdjust) /
1440

Integer8Date
= CDate(lngDate
)
End Function


I pass the value from pwdLastSet property to this function to get the date/time value. After a couple of Google searches, I chanced upon a forum post by Brandon Shell - Microsoft PowerShell MVP. The entire function can be summed up in just a line

[datetime]::FromFileTimeUTC($objItem.pwdlastset[0])

This is if you are using the System.DirectoryServices.DirectorySearcher class and not the
System.DirectoryServices.DirectoryEntry in the .NET Framework which is available in PowerShell. The DateTime.FromFileTimeUtc Method converts the specified Windows file time to an equivalent UTC time. So much for using conversion functions in VBScript to do this.

No comments:

Google