Home » c# » C# – Return Custom Security Groups from Active Directory-Exceptionshub

C# – Return Custom Security Groups from Active Directory-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I currently have the following code which successfully gets all Security Groups from AD and adds them into a Check List box:

try
{
    Logging.LogMessageToFile("Reading Security Groups from AD.");
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

    foreach (var found in srch.FindAll())
    {
        lstAdGroups.Items.Clear();
        lstAdGroups.Items.Add(found);     
    }
}
catch (Exception ex)
{
    Logging.LogMessageToFile("Unexpected error reading Security Groups from AD: " + ex.Message);
}

My issue is that it currently pulls every Security Group (where ideally I’d only like to only list custom created security groups (eg, exclude any from the Users or Builtin OU’s). I can’t see if there are any properties against groups to filter ‘custom’ from out the box. Is this even possible?

How to&Answers:

PrincipalSearcher can only filter based on attributes that are exposed in properties of the various Principal classes. If you’re looking for groups, you’re limited to filtering based on the properties of the GroupPrincipal class.

That issues aside, filtering out objects in certain OUs isn’t something you can do in a query at all simply because there is no AD attribute that contains the OU that you’re allowed to filter on. So there is two ways you can do this:

  1. Do what you’re already doing, but in your loop, look at the DistinguishedName property of the result. If it’s in an OU you don’t like, then just continue;.

  2. You can use DirectorySearcher directly (which is what PrincipalSearcher uses in the background anyway), and filter by the isCriticalSystemObject attribute. That will filter out built-in objects like the Domain Admins and Users groups, etc.

Here is a simple example using DirectorySearcher that just outputs the name of each group:

var searcher = new DirectorySearcher("(&(objectClass=group)(!isCriticalSystemObject=TRUE))");

using (var results = searcher.FindAll()) {
    foreach (SearchResult result in results) {
        Console.WriteLine(result.Properties["cn"][0]);
    }
}