To get all groups in Active Directory i have write this code in C#. It works perfectly well as i dont need to pass any servername, OU, DC etc.
UserPrincipal current_user = UserPrincipal.Current;
PrincipalContext current_context = current_user.Context;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeUser = new GroupPrincipal(ctx);
Principal userOrGroup = qbeUser as Principal;
userOrGroup.Name = "*";
PrincipalSearcher searcher = new PrincipalSearcher(userOrGroup);
List<string> AllGroups = new List<string>();
// enumerate the results - you need to check what kind of principal you get back
foreach (Principal found in searcher.FindAll())
{
// is it a UserPrincipal - do what you need to do with that...
if (found is UserPrincipal)
{
// ......
}
else if (found is GroupPrincipal)
{
AllGroups.Add(found.Name);
//GroupPrincipal gp = found as GroupPrincipal;
//var data = gp.GetMembers();
// if it's a group - do whatever you need to do with a group....
}
}
//return AllGroups;
The problem is that it list too many groups that i dont need like
PerformanceLogUsers, SchemaAdmins, HelpServiceGroups, Telnet Clients and so on.
I only need groups like Administrator, Guests and other user created group. I have read about something like these are special group and etc etc.
Any help in this regard is highly appreciated.
AD doesn’t discriminate by group relevance when performing searches. It’s either a group or it isn’t. However, you can specify whether or not to return security groups or distribution groups, for instance.
How your directory is currently set up, is another matter. If the groups you want and the groups you don’t want are both “Security Groups”, then it’ll pose a problem.
One solution to that would be finding some unique attribute that your relevant groups have in common (or create one) and then filter on the existence of those.