We help IT Professionals succeed at work.

How can I get a list of AD groups that match a partial name?

Elliott Ward
Elliott Ward used Ask the Experts™
on
I need to search AD for any groups that match a partial name, then search each group for the users inside it.

I have the code to list the users in a group, listed below.  But how do I get the listing of the groups to search?

Public Function UsersInActiveDirectoryGroup(ByVal GroupName As String) As Specialized.StringCollection
   Dim members As New Specialized.StringCollection

   Try
       Dim domainContext As New ActiveDirectory.DirectoryContext(ActiveDirectory.DirectoryContextType.Domain)
       Using dc As ActiveDirectory.DomainController = ActiveDirectory.DomainController.FindOne(domainContext)
           Using pctx As New PrincipalContext(ContextType.Domain, dc.Domain.Name)
                Using grp As GroupPrincipal = GroupPrincipal.FindByIdentity(pctx, IdentityType.Name, GroupName)
                    If Not IsNothing(grp) Then
                        For Each p As Principal In grp.GetMembers(True)
                             members.Add(p.SamAccountName)
                        Next
                     End If
                 End Using
             End Using
         End Using
         Return members
     Catch ex As Exception
         Return Nothing
     End Try
 End Function
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014

Commented:
Here is a comprehensive tutorial. See if it helps

http://www.codeproject.com/KB/system/everythingInAD.aspx
ThinkPaperIT Consultant

Commented:
I'm not too familiar with this kind of code in general, but the main thing you would add is:

samAccountName=*BLAH*

where "BLAH" is the name you want it to match.
Dont know how big of a userbase you got . but i normally use the manage engine ad manager plus to get all kinds of reports . They also have a free version for 100 users or so ..
ADManager Plus- Active Directory Management & Reporting
http://www.manageengine.com/products/ad-manager/
Ad Manager Plus
Software Developer
Commented:
Here is the solution I am using:

Dim UsersPrincipal As UserPrincipal = New UserPrincipal(pctx)        
Dim insGroupPrincipal As New GroupPrincipal(pctx)

insGroupPrincipal.Name = "Hyperion*"
ADSearchGroups = SearchGroups(insGroupPrincipal)

For Each sGroup As String In ADSearchGroups
    For Each sUser As String In sUsers
    Next
Next
Elliott WardSoftware Developer

Author

Commented:
Thanks for your help.