Redth
Redth

Reputation: 5544

Search Active Directory for an OU using a partial path to the OU

Is there a way in AD Query syntax, to find an OU's full path by searching on its partial path?

For example, the full path to my OU is:

OU=Clerks,OU=OfficeA,OU=Administration,DC=domain,DC=local

Now, I'd like to try and search and find that object by using the partial path:

OU=Clerks,OU=OfficeA

I'd like to be able to search something like:

(&(objectCategory=organizationalUnit)(path=Clerks/OfficeA*))

I can't find any syntax examples of how to accomplish something like this. A program I'm developing requires that I get the paths to a lot of OU's which all have a common structure in the last two levels of OU's, however they can be nested at any given depth in the domain otherwise. If I can search somehow like this, it would be easy to get the full path just searching by the last two OU nested levels.

Upvotes: 1

Views: 10831

Answers (1)

JPBlanc
JPBlanc

Reputation: 72680

The thing you want to do exists on pure LDAP implementation it's a feature called ExtensibleMatch wich seems to be correctly explained in this wiki article . You will also found something helpfull examples here.

But it's not present in Active-Directory

So here is a method writen in C# that exploit the Parent propertie of a DirectoryEntry.

   static List<DirectoryEntry> OuInTheFormOf(DirectoryEntry deBase, string ou1, string ou2)
    {
      List<DirectoryEntry> deList = null;

      /* Directory Search
       */
      DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
      dsLookFor.Filter = ou1;
      dsLookFor.SearchScope = SearchScope.Subtree;
      dsLookFor.PropertiesToLoad.Add("ou");

      SearchResultCollection srcOUs = dsLookFor.FindAll();

      if (srcOUs.Count != 0)
      {
        deList = new List<DirectoryEntry>();

        foreach (SearchResult srOU in srcOUs)
        {
          DirectoryEntry deOU = srOU.GetDirectoryEntry();
          if (deOU.Parent.Name.ToUpper() == ou2.ToUpper())
            deList.Add(deOU);
        }
      }
      return deList;
    }

Here is the usage :

  /* Connection to Active Directory
   */
  DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr");

  List<DirectoryEntry> l = OuInTheFormOf(deBase, "ou=Clerks", "ou=OfficeA");

  foreach (DirectoryEntry deTmp in l)
  {
    Console.WriteLine(deTmp.Properties["distinguishedName"].Value);
  }

Upvotes: 2

Related Questions