Reputation: 1132
I'm trying to create an ldap query to search Active Directory and filter the results to only return users that have a lastLogonTimestamp field with a value older than 30 days.
The ldap filter that I'm looking for is something like this:
"(&(ObjectClass=User)(lastLogonTimestamp<=" + lastLogonTimeStampLimit + "))"
My problem is that I have not been able to find any way to convert a .net DateTime value to the correct format for the lastLogonTimestamp field within Active Directory, which I've read is a 'Integer8' data type.
If it helps any, I've found a conversion to go the other way:
DateTime.FromFileTime((long)(user.Properties["lastLogonTimestamp"][0]))
Upvotes: 0
Views: 4182
Reputation: 5391
This code works to convert the AD object to a valid DateTime. You can use it for any of the date values in AD (this example is for lastLogon). The key seems to be the ActiveDs library. The long
cast doesn't seem to work, but IADsLargeInteger
does just fine!
Here is a code sample including everything you need to convert from the AD type to a DateTime:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using ActiveDs; // Namespace added via ref to C:\Windows\System32\activeds.tlb
private DateTime? getLastLogin(DirectoryEntry de)
{
Int64 lastLogonThisServer = new Int64();
if (de.Properties.Contains("lastLogon"))
{
if (de.Properties["lastLogon"].Value != null)
{
try
{
IADsLargeInteger lgInt =
(IADsLargeInteger) de.Properties["lastLogon"].Value;
lastLogonThisServer = ((long)lgInt.HighPart << 32) + lgInt.LowPart;
return DateTime.FromFileTime(lastLogonThisServer);
}
catch (Exception e)
{
return null;
}
}
}
return null;
}
Upvotes: 1