如何使用PrincipalSearchResult搜索活动目录,不包括VB.NET中的某些OU

时间:2013-09-13 22:04:21

标签: .net vb.net

我正在使用此代码在活动目录中搜索用户帐户,该工作正常。

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

问题是我想要的用户帐户可能在几个地方,所以我不想指定要搜索的OU,但它可能在2个OU中,我不希望它从中返回。有没有办法从我的搜索中排除这两个OU?

我发现了一些类似的问题,但没有一个以这种方式使用VB.Net和system.directory.accountmanagement命名空间。

2 个答案:

答案 0 :(得分:0)

Dim reduce = results.Where(Function(p) p.SamAccounNams = "Name").FirstOrDefault

好的,然后这样做

Dim reduce results.Where(Function(p) Not p.DistinguishedName.Contains("OU=UnwantedOU1") and Not p.DistinguishedName.Contains("OU=UnwantedOU").ToList()

这将为您提供不在两个不需要的OU中的所有用户。

祝你好运

答案 1 :(得分:0)

我想通过在我的搜索结果中添加DistinguishedName并检查我想要排除的OU来做我想做的事情。这是完全有效的例子。

Dim insPrincipalContext As New PrincipalContext(ContextType.Domain, Environment.UserDomainName, "DC=Mydomain,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
        adDistName = currentADUser.DistinguishedName
        If InStr(adDistName, "OU=UnwantedOU1") Or InStr(adDistName, "OU=UnwantedOU2") Then
            Continue For
        Else
            adUsername = currentADUser.SamAccountName
            adLast = currentADUser.Surname
            adFirst = currentADUser.GivenName
            adMail = currentADUser.EmailAddress
            Exit For
        End If
    Next