2013-02-05 88 views
0

我正在嘗試使用活動目錄獲取用戶信息。大多數情況下,它工作。問題是我似乎無法得到用戶上次登錄日期。任何人有任何建議?我的代碼如下:如何獲取用戶上次登錄的Active Directory

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 

回答

0

您是否嘗試過'lastLogon'LDAP屬性?你的代碼看起來不錯,我猜你只是不確定信息存儲在AD中的什麼位置?

+0

感謝Mark的迴應。我是使用AD的新手,所以我不確定我在做什麼。它一直在山上。任何方式,我已經嘗試了lastLogon屬性,但它總是返回null。我知道它應該有價值,因爲我用我的帳戶進行測試,每天都記錄下來。 – jason

+0

幾年前,我已經爲內部電話目錄完成了LDAP的工作,這有點麻煩;這傢伙的網站是非常有用的,他有一些信息,爲什麼lastLogon可能不適合你:http://www.computerperformance.co.uk/ezine/ezine85.htm – markp3rry

+0

如果有幫助,請不要忘記upvote: ) – markp3rry

1

作品對我來說:

  1. 加載屬性:

    osearcher.PropertiesToLoad.Add("lastLogon") 
    
  2. 訪問它:

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

注意你會得到一個區間值。這是64位,我認爲沒有簽名。 .NET中有一些強制轉換方法,但它們只採用帶符號的64位。還沒有檢查未來多少年,這將是一個問題之前!

此外,如果您使用DirectoryServices中較新的UserPrincipal,那麼它將得到lastlogon,它返回一個可爲空的日期。

相關問題