Friday, 13 September 2013

How to search active directory with PrincipalSearchResult excluding certain OUs in VB.NET

How to search active directory with PrincipalSearchResult excluding
certain OUs in VB.NET

I am searching for user accounts in active directory with this code, which
works just fine.
Dim insPrincipalContext As New PrincipalContext(ContextType.Domain,
Environment.UserDomainName, "DC=domain,DC=com")
Dim insUserPrincipal As New UserPrincipal(insPrincipalContext)
insUserPrincipal.Description = empID
Dim insPrincipalSearcher As New PrincipalSearcher()
Dim currentADUser As
System.DirectoryServices.AccountManagement.UserPrincipal
insPrincipalSearcher.QueryFilter = insUserPrincipal
Dim results As PrincipalSearchResult(Of Principal) =
insPrincipalSearcher.FindAll
For Each p As Principal In results
currentADUser = p
adUsername = currentADUser.SamAccountName
adLast = currentADUser.Surname
adFirst = currentADUser.GivenName
adMail = currentADUser.EmailAddress
Next
The problem is that the user account I want could be in several places, so
I don't want to specify an OU to search, but it could be in 2 OUs that I
do not want it to be returned from. Is there a way to exclude these 2 OUs
from my search?
I have found some similar questions but none that were using VB.Net and
the system.directory.accountmanagement namespace in this way.

No comments:

Post a Comment