• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 10
  • Last Modified:

Return all security groups within a specific OU in which a specific user is a member of

Need to create a function that accepts a username and returns the names of the security groups in a specific OU in which the user is a member.
0
dmoss123
Asked:
dmoss123
1 Solution
 
Chris DentPowerShell DeveloperCommented:
In what language? The most popular .NET languages are probably VB, C# and PowerShell.

If you're building the code yourself, you need to:

1. Construct System.DirectoryServices.Directory entry for the root of the domain.
2. Construct System.DirectoryServices.DirectorySearcher with the entry above and the LDAP filter "(samAccountName=<Username>)".
3. Call FindOne() on the DirectorySearcher and test you have a SearchResult
4. Pick the distinguishedname attribute from the search result (the users DN)
5. Build an LDAP filter to query member "(&(objectClass=group)(member=<DNFromTheQueryAbove>))"
6. Construct System.DirectoryServices.DirectoryEntry with (LDAP://<DistinguishedName of Specific OU>).
7. Construct System.DirectoryServices.DirectorySearcher with the Directory entry and the LDAP filter created in 5.
8. Call FindAll() on the DirectorySearcher to get a SearchResultCollection
9. Extract the properties you wish to see (SearchResult.Properties and the name key).

C# kind of looks something like (completely untested, may contain blatant syntax errors):
using System;
using System.Collections;
using System.DirectoryServices;

public class AD {
  public static String[] GetMemberOf (String Username) {
    DirectoryEntry DomainRoot = new DirectoryEntry();
    String LdapFilter = String.Format("(samAccountName={0})", Username);
    DirectorySearcher Searcher = new DirectorySearcher(DomainRoot, LdapFilter);
    Searcher.PageSize = 1000;
    
    SearchResult ADUser = Searcher.FindAll();
    
    if (ADUser != null) {
      String UserDN = ADUser.Properties["distinguishedname"][0];
      
      LdapFilter = String.Format("(&(objectClass=group)(member={0}))", UserDN);
      DirectoryEntry TargetOU = new DirectoryEntry("LDAP://<OU-PATH>");
      
      Searcher.SearchRoot = TargetOU;
      Searcher.Filter = LdapFilter;
      
      SearchResultCollection ADGroups = Searcher.FindAll();
      
      ArrayList ADGroupList = new ArrayList();
      
      foreach (SearchResult ADGroup in ADGroups) {
        ADGroupList.Add(ADGroup.Properties["name"][0]);
      }
      
      return ADGroupList.ToArray();
    }
  }
}

Open in new window

Chris
0

Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now