Sunday 4 December 2011

WORKING WITH ACTIVE DIRECTORY LASTLOGONTIMESTAMP ATTRIBUTE


WORKING WITH ACTIVE DIRECTORY LASTLOGONTIMESTAMP ATTRIBUTE:



Active Directory includes an attribute – lastLogon – that tells you the last time a user or computer logged on.
The lastLogon attribute is not replicated from one domain controller to another.
There’s a brand-new attribute in the schema: lastLogonTimestamp.
This attribute also keeps track of the last time a user logged on to the domain, but this new attribute is replicated from one domain controller to another.
The lastLogonTimestamp is replicated only once every 14 days. This helps limit replication traffic.
The lastLogonTimestamp is stored as a 64-bit integer. When you query the lastLogonTimestamp you don’t get back a date-time like May 15, 2005 8:05 AM. Instead, you get back the number of 100-nanosecond intervals that passed between January 1, 1601 and the time the user last logged on.

Incidentally,VBScript can’t actually handle the 64-bit integer returned by lastLogonTimestamp.
But at least there is a workaround for this: ADSI’s IADsLargeInterger interface can break this into a pair of 32-bit integers for us.

---------------------------------------------------------------------------------------------------------------------------------
This code will bind to the user account in Active Directory and then use the Get method to retrieve the lastLogonTimestamp, storing that value in an IADsLargeInteger object with the object reference objLastLogon.

Set objUser = GetObject("LDAP://cn=Ken Myer, ou=Finance, dc=fabrikam, dc=com")
Set objLastLogon = objUser.Get("lastLogonTimestamp")

'The IADsLargeInteger object has two properties: HighPart, which stores the upper 32 bits of our 64-bit integer;
'and LowPart, which stores the lower 32 bits of the integer.

intLastLogonTime = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart

'There are 1,000,000,000 nanoseconds in a second, 60 seconds in a minute and 1,440 minutes in every 24-hour day.
'This line of code tells us how many days have elapsed.

intLastLogonTime = intLastLogonTime / (60 * 10000000)
intLastLogonTime = intLastLogonTime / 1440

'Add the number of days that passed to the date January 1, 1601.

Wscript.Echo "Last logon time: " & intLastLogonTime + #1/1/1601#


Output:
Last logon time: 4/25/2005 2:54:09 PM

---------------------------------------------------------------------------------------------------------------------------------

Alternate solution:

'Use a method on DateTime called FromFileTime(long nanotime).This method returns a DateTime using
'the current Time Zone, so we don’t have to convert it.

Dim lastLogonDateTime As DateTime

Set objUser = GetObject("LDAP://cn=Ken Myer, ou=Finance, dc=fabrikam, dc=com")
Set objLastLogon = objUser.Get("lastLogonTimestamp")

lastLogonDateTime = DateTime.FromFileTime(objLastLogon)

Wscript.Echo "Last logon time: " & lastLogonDateTime.ToString

No comments:

Post a Comment