Get LDAP Full Name from LDAP username


/ Published in: Visual Basic
Save to your folder(s)

This function is very rough and right now is hard coded to return the common name. This can be useful if, for example, you have a list of usernames in Excel and you want to get the name of the person. However, it can be used in any VBA application.


Copy this code and paste it in your HTML
  1. Function getLDAPName(clockNumber As String)
  2. '
  3. 'Declare Variables
  4. Dim objAdoCon, objAdoCmd, objAdoRS
  5. Dim objUser, objRootDSE
  6. Dim strDomainDN, strUserFullName
  7. Dim intAnswer As Integer
  8. On Error GoTo Err_NoNetwork
  9. ' Get current logged in user name
  10. 'strUserFullName = Environ("UserName")
  11.  
  12. ' Get the DN of the user's domain
  13. Set objRootDSE = GetObject("LDAP://rootDSE")
  14. strDomainDN = objRootDSE.Get("defaultNamingContext")
  15.  
  16. ' Search the domain for the user's account object
  17. Set objAdoCon = CreateObject("ADODB.Connection")
  18. objAdoCon.Open "Provider=ADsDSOObject;"
  19.  
  20. Set objAdoCmd = CreateObject("ADODB.Command")
  21. Set objAdoCmd.ActiveConnection = objAdoCon
  22.  
  23. objAdoCmd.CommandText = _
  24. "SELECT ADsPath FROM 'LDAP://" & strDomainDN & "' WHERE " & _
  25. "objectCategory='person' AND objectClass='user' AND " & _
  26. "sAMAccountName='" & clockNumber & "'"
  27.  
  28. Set objAdoRS = objAdoCmd.Execute
  29.  
  30. ' If found, get the displayName attribute.
  31.  
  32. If (Not objAdoRS.EOF) Then
  33. Set objUser = GetObject(objAdoRS.Fields("ADsPath").Value)
  34.  
  35. 'Get common name
  36. objUser.GetInfoEx Array("CN"), 0
  37. commonName = objUser.Get("CN")
  38.  
  39. 'get first name
  40. objUser.GetInfoEx Array("givenName"), 0
  41. firstName = objUser.Get("givenName")
  42.  
  43. 'get last name
  44. objUser.GetInfoEx Array("SN"), 0
  45. lastName = objUser.Get("SN")
  46.  
  47. 'get display name
  48. objUser.GetInfoEx Array("DisplayName"), 0
  49. DisplayName = objUser.Get("DisplayName")
  50.  
  51. Set objUser = Nothing
  52. getLDAPName = commonName
  53.  
  54. Else
  55. ' handle "not found" error here
  56. GoTo Err_NoNetwork
  57. End If
  58.  
  59. Set objAdoRS = Nothing
  60. Set objAdoCmd = Nothing
  61. objAdoCon.Close
  62. Set objAdoCon = Nothing
  63.  
  64. Set objRootDSE = Nothing
  65. Set WshNetwork = Nothing
  66. GoTo Exit_Sub
  67.  
  68. Exit_Sub:
  69. Exit Function
  70.  
  71. Err_NoNetwork:
  72. getLDAPName = "Error"
  73. GoTo Exit_Sub
  74. End Function

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.