0

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
4

2 回答 2

1

为我工作:

  1. 加载属性:

    osearcher.PropertiesToLoad.Add("lastLogon")  
    
  2. 访问它:

    dim myDateInterval = result.Properties("lastLogon").Item(0)
    

请注意,您将获得一个区间值。我认为它是 64 位的,未签名的。.NET 中有一些转换方法,但它们只采用带符号的 64 位。在它成为问题之前,还没有检查过这会提前多少年!

此外,如果您使用 DirectoryServices 中较新的 UserPrincipal ,则其中包含 lastlogon ,这将返回一个可为空的日期。

于 2016-05-18T01:09:37.760 回答
0

您是否尝试过“lastLogon”LDAP 属性?您的代码看起来不错,我猜您只是不确定信息在 AD 中的存储位置?

于 2013-02-05T14:04:00.987 回答