AD PrincipalSearcher: Search where property does not contain some value

4.1k views Asked by At

Principal Searcher seems to do a great job when building a filter to find an object with a particular value. What about without? For example How do I build a filter to exclude everyone with "Joe" in their name. The code below would not work.

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal qbeUser = new UserPrincipal(ctx);
        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

         //this is the problem line.  How to format to exclude values with Joe?
         qbeUser.Name != "*Joe*"; 

        srch.QueryFilter = qbeUser;
        foreach (var found in srch.FindAll())
         { do something to non Joe users... }

....

1

There are 1 answers

1
baldpate On

Seems it's not possible with PrincipalSearcher.

Two possible workaround:

  1. Use PrincipalSearcher to get all users and filter at client side

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    UserPrincipal qbeUser = new UserPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
    
    srch.QueryFilter = qbeUser;
    foreach (var found in srch.FindAll())
    { //filter out users with "Joe" in its name }
    
  2. Use DirectorySearcher

    DirectoryEntry de = new DirectoryEntry("LDAP://domain.com/dc=domain,dc=com", "user", "pwd");
    DirectorySearcher srch = new DirectorySearcher(de);
    
    srch.Filter = "(&(objectCategory=person)(objectClass=user)(!(name=*Joe*)))";
    srch.SearchScope = SearchScope.Subtree;
    // add the attributes
    srch.PropertiesToLoad.Add("distinguishedName");
    using (SearchResultCollection results = srch.FindAll())
    {
        foreach (SearchResult result in results)
        {
            string dn = result.Properties["distinguishedName"][0] as string;
            Console.WriteLine("- {0}", dn);
        }
    }