I need to write a C# script that returns all the Active Directory groups with group names that start with a certain name. I know can return one group using the following code.
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "Groupname");
However, I want all the groups where the Groupname starts with, say "GroupPrefix". I then want to traverse all these groups using the following code and store the "members" in an array/list that I can use later for searching.
foreach (UserPrincipal p in grp.GetMembers(true))
I would much appreciate any help that I can get with this.
View all groups You can see all the groups for your organization in the Groups - All groups page of the Azure portal. Go to Azure Active Directory > Groups. The Groups - All groups page appears, showing all your active groups.
To find AD groups with PowerShell, you can use the Get-ADGroup cmdlet. With no parameters, Get-ADGroup will query AD and return all groups in a domain using the Filter parameter. The Filter parameter is required.
Open the properties dialog of the Active Directory group whose objectGUID you need to find, and navigate to the Attribute Editor tab. In this list, in alphabetical order, you can find the objectGUID value for the group.
To get the local groups on the windows system using PowerShell, you can use the Get-LocalGroup (Module: Microsoft. PowerShell. LocalAccounts) command. This command will list down all the groups on the particular system.
You can use a PrincipalSearcher
and a "query-by-example" principal to do your searching:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for a GroupPrincipal
// and with the name like some pattern
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.Name = "GroupPrefix*";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal"
}
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement
. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.
Of course, depending on your need, you might want to specify other properties on that "query-by-example" group principal you create:
DisplayName
(typically: first name + space + last name)SAM Account Name
- your Windows/AD account nameYou can specify any of the properties on the GroupPrincipal
and use those as "query-by-example" for your PrincipalSearcher
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With