Getting all Active Directory Properties with DirectorySearcher

2k views Asked by At

I am accessing Active Directory. If I call it like this

DirectorySearcher srch = new DirectorySearcher(de);

//Filter to return only users and deleted users and not system accounts
srch.Filter = "(|(&(objectCategory=person)(objectClass=user)(sn=*))(&(isDeleted=TRUE)(objectClass=user)))";
srch.SearchScope = SearchScope.OneLevel;
srch.ExtendedDN = ExtendedDN.Standard;
srch.FindAll();

then it returns a list of users with some of the properties... I want to see the "whenChanged" property but when i try adding the line

srch.PropertiesLoad.Add("whenChanged");

then it doesn't return any users. Could this be due to deleted user's not having that property and that it can't uniformly apply all the properties so it returns 0 results? How can I view all the users, both deleted and active and see the "whenChanged" property for all even it results in a null

1

There are 1 answers

0
baldpate On

Several points:

  • To get deleted objects you need to set srch.Tombstone = true;
  • Deleted objects are stored under "CN=Deleted Objects,DC=domain,DC=com".
    So to search for all users plus deleted objects, would better use domain root as search root and use SearchScope.Subtree as scope
  • Any attributes added to DirectorySearcher.PropertiesLoad should not remove any results.
    This may due to reason other than srch.PropertiesLoad.Add("whenChanged");
  • Why put sn=* in search? this filter out users whose last name is not set.
    Is this intended?

Tested following code that can get the users plus deleted user successfully, plus obtain the "whenChanged" property. Please give a try.

DirectoryEntry de = new DirectoryEntry("LDAP://domain.com/dc=domain,dc=com", "user", "pwd");
DirectorySearcher srch = new DirectorySearcher(de);

//Filter to return only users and deleted users and not system accounts
srch.Filter = "(|(&(objectCategory=person)(objectClass=user)(sn=*))(&(isDeleted=TRUE)(objectClass=user)))";
srch.SearchScope = SearchScope.Subtree;
srch.ExtendedDN = ExtendedDN.Standard;
srch.Tombstone = true;
srch.PropertiesToLoad.Add("whenChanged");
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);

        ResultPropertyValueCollection prop = result.Properties["whenChanged"];
        if (prop != null)
        {
            Console.WriteLine("  {0}", (DateTime)prop[0]);
        }
    }
}