Getting AD Details based on username

active-directory, vba, vbscript

Solution

LDAP URIs require a distinguished name. Account names won't work. If you want to get user objects based on the account name you need a "regular" LDAP query:

username = "SomeUserName"

Set rootDSE = GetObject("LDAP://RootDSE")
base  = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"
'filter on user objects with the given account name
fltr  = "(&(objectClass=user)(objectCategory=Person)" & _
        "(sAMAccountName=" & username & "))"
'add other attributes according to your requirements
attr  = "distinguishedName,sAMAccountName"
scope = "subtree"

Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"

Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = base & ";" & fltr & ";" & attr & ";" & scope

Set rs = cmd.Execute
Do Until rs.EOF
  WScript.Echo rs.Fields("distinguishedName").Value
  rs.MoveNext
Loop
rs.Close

conn.Close

Since I got annoyed from having to write all that boilerplate code over and over again, I wrapped it in a class (`ADQuery`) some time ago.

Problem

I have a code to retrieve the details of a user from the AD such as email address, phone number etc, etc. The codes I am currently using is: ``` Set objSysInfo = CreateObject("ADSystemInfo") strUser = objSysInfo.UserName msgbox(strUser) Set objUser = GetObject("LDAP://" & strUser) ``` It gets the currently logged in user's details. But what I need to do now is to parse in the user's username and retrieve the details based on that. I have tried to change objSysinfo.UserName to the username and it returned blank. ``` Set objSysInfo = CreateObject("ADSystemInfo") strUser = "SomeUserName" msgbox(strUser) Set objUser = GetObject("LDAP://" & strUser) ``` How should I go about retrieving the details from the AD based on a user name provided?

Original source