简体   繁体   中英

DirectorySearcher: How to get only entries for “real” users

I use a DirectorySearcher to get all users from Active Directory - but I need to get only "real" users.

Filter:

search.Filter = "(&(objectClass=user)(objectCategory=person))";

but I get all user accounts, like:

henry.miller            <-wanted
ernest.hemingway        <-wanted
HealthMailboxced7671    <-not wanted 

Question: how does my filter need to be modified to return only real users?

My whole code:

string DomainPath = "LDAP://DC=writers,DC=local";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");

SearchResult result;

SearchResultCollection resultCol = search.FindAll();

if (resultCol != null)
{
    for (int counter = 0; counter < resultCol.Count; counter++)
    {
        result = resultCol[counter];

        if (result.Properties.Contains("samaccountname"))
        {
            Console.WriteLine((String)result.Properties["samaccountname"][0]);
        }
    }
}

Try below using LDAP

 (&(objectCategory=person)(objectClass=user)(sAMAccountName=*)(!(cn=*O*)))

Just for info - CN is Common Name. You can get more info on LDAP here

You also asked me with what property can you retrieve cn. Here you can extract by this code snippet ( for double check). But as far as I know it is CN only

 foreach (string property in result.Properties.PropertyNames)
{
      foreach (Object propertyValue in result.Properties[property])
     {
        // print out the Property Value here
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM