[英]How to get users last logon from Active Directory
I am trying to work with active directory to get users information. 我正在尝试使用活动目录来获取用户信息。 For the most part, it's working. 在大多数情况下,它是有效的。 The problem is I cant seem to get a users last logon date. 问题是我似乎无法获得用户的上次登录日期。 Anyone have any suggestions? 有人有什么建议吗? My code is as follows: 我的代码如下:
Public Shared Function GetUsersByUsername(ByVal Username As String) As ADUser
Dim myUser As New ADUser
Dim oroot As DirectoryEntry = New DirectoryEntry("GC://ldap.myCompany.com")
Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
Dim result As SearchResult
osearcher.Filter = String.Format("(&(SAMAccountName={0}))", Username)
osearcher.PropertiesToLoad.Add("cn")
osearcher.PropertiesToLoad.Add("SAMAccountName") 'Users login name
osearcher.PropertiesToLoad.Add("givenName") 'Users first name
osearcher.PropertiesToLoad.Add("sn") 'Users last name
osearcher.PropertiesToLoad.Add("mail") 'Email address
osearcher.PropertiesToLoad.Add("accountExpires") 'expiration date
result = osearcher.FindOne
Try
Dim userPath As String() = result.Path.ToString.Split(New Char() {","c})
Dim parsedString As String
Dim User As DirectoryEntry
Dim expirationDate As String
User = result.GetDirectoryEntry()
myUser.UserID = result.Properties("cn").Item(0)
myUser.EmailAddress = result.Properties("mail").Item(0)
myUser.FirstName = result.Properties("givenName").Item(0)
myUser.LastName = result.Properties("sn").Item(0)
expirationDate = result.Properties("accountExpires").Item(0)
If (isAccountLocked(User) = True) Then
myUser.Status = ADUser.AccountStatus.Locked
ElseIf (isAccountEnabled(User) = False) Then
myUser.Status = ADUser.AccountStatus.Disabled
ElseIf (isAccountExpired(expirationDate) = True) Then
myUser.Status = ADUser.AccountStatus.Expired
Else
myUser.Status = ADUser.AccountStatus.Active
End If
parsedString = userPath((userPath.Length - 3))
myUser.Domain = parsedString.Substring(3, parsedString.Length - 3)
Catch ex As Exception
Return Nothing
End Try
Return myUser
End Function
works for me: 为我工作:
Load the property: 加载属性:
osearcher.PropertiesToLoad.Add("lastLogon")
Access it: 访问它:
dim myDateInterval = result.Properties("lastLogon").Item(0)
Note you'll get back an interval value. 请注意,您将获得一个间隔值。 It's 64-bit, unsigned, I think. 我认为它是64位无符号的。 There are some casting methods in .NET, but they only take signed 64-bit. .NET中有一些强制转换方法,但它们仅采用带符号的64位。 Haven't checked how many years ahead that would be before it was an issue! 在问题尚未解决之前,还没有检查多少年!
Also, if you use the newer UserPrincipal from DirectoryServices then it's got lastlogon in it, that returns a nullable date. 另外,如果您使用DirectoryServices中较新的UserPrincipal,则会在其中获得lastlogon,该日期将返回可为空的日期。
Have you tried the 'lastLogon' LDAP attribute? 您是否尝试过“ lastLogon” LDAP属性? Your code looks good, I'm guessing you're just not sure where the information is stored in AD? 您的代码看起来不错,我猜您只是不确定该信息在AD中的存储位置?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.