How to search entire domain for a user in AD using VB.NET

Go To StackoverFlow.com

2

I understand how to find a user using the exact LDAP url

LDAP://domain/CN=Username,OU=Users,DC=domain,DC=com

but what if I need to find a user without looking in the particular OU. How do I search the entire domain?

2012-04-04 18:01
by Pickle


3

If you're using .NET 3.5 or newer, you should check out the PrincipalSearcher class:

' create your domain context
Dim ctx As New PrincipalContext(ContextType.Domain)

' define a "query-by-example" principal - here, we search for a UserPrincipal 
' and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
Dim qbeUser As New UserPrincipal(ctx)
qbeUser.GivenName = "Bruce"
qbeUser.Surname = "Miller"

' create your principal searcher passing in the QBE principal    
Dim srch As New PrincipalSearcher(qbeUser)

' find all matches
For Each found As var In srch.FindAll()
    ' do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
Next

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:

  • DisplayName (typically: first name + space + last name)
  • SAM Account Name - your Windows/AD account name
  • User Principal Name - your "username@yourcompany.com" style name

You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.

Or if you want to find just a specific user - try this:

' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, "SomeUserName")

' do something here....     
If user IsNot Nothing Then
   . .....
End If
2012-04-04 19:23
by marc_s


0

Just omit the OU structure from the LDAP path. This will set the search at the root of the domain.

LDAP://DC=domain,DC=com

and use a filter to find the specific user:

(&(objectClass=User)(cn=" & susername & "))
2012-04-04 18:17
by Tom Pickles
Note that the search scope should be sub in this example - Terry Gardner 2012-04-04 19:26
So using Tom Pickles' suggestion, I came up with thi - Pickle 2012-04-05 00:01
Ads