Getting AD Details based on username Getting AD Details based on username vba vba

Getting AD Details based on username


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 namefltr  = "(&(objectClass=user)(objectCategory=Person)" & _        "(sAMAccountName=" & username & "))"'add other attributes according to your requirementsattr  = "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 = conncmd.CommandText = base & ";" & fltr & ";" & attr & ";" & scopeSet rs = cmd.ExecuteDo Until rs.EOF  WScript.Echo rs.Fields("distinguishedName").Value  rs.MoveNextLooprs.Closeconn.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.


Just an extra comment to Ansgar the RootDSE is great if you only have one domain. You can modify his code to point else where:

    base  = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"

to something like:

    base  = "<LDAP://" & "DC=corp,DC=foo,DC=com" & ">"

if your domain AD domain is corp.foo.com