Search code examples
vb.netdirectoryservicesdistribution-list

Sublists in Distribution Lists using DirectoryServices


This is a win form I am building from .Net and I need to get the members of each security group. Some of our security groups have subgroups and I need the program to be able to distinguish that and run through the members of a sub group.

Here is my code:

Dim thisDL As String = cmbADGroups.GetItemText(cmbADGroups.SelectedItem)
Dim dn As String = "CN=" & thisDL & ",OU=DistributionLists,DC=ThisDC,DC=com"
Dim ctx As PrincipalContext = New PrincipalContext(ContextType.Domain)
Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, 3, dn)
Dim members As PrincipalSearchResult(Of Principal) = group.GetMembers()
Dim PersonList = (From m In members
                  Order By m.DisplayName
                  Select New OaklawnPerson With {.userFullName = m.DisplayName,
                                                 .userID = m.SamAccountName,
                                                 .userEmail = m.UserPrincipalName,
                                                 .userFirstName = m.DisplayName.Split(",").Last()}).ToList
dgvSearchResults.DataSource = OaklawnPersonList

My question:
This works when there are not any sub-distribution lists under, however when there is one or more sublists, I need to identify that it is indeed a sublist and get members from it (and even if there is a sub of a sub).
I am not asking for anyone to write code for me, but maybe point me in the direction I need to go. Thanks for the information


Solution

  • The results will be of type Principal, but if it's a group you will see that it's a GroupPrincipal. I'm primarily a C# developer, but it would be something like:

    If TypeOf m Is GroupPrincipal Then ...
    

    then you can treat it as a group. I'm not sure you can pull that off in a Linq query, so you might be better off changing that to a For Each loop.

    I have some example code to do this directly with DirectoryEntry (which is what GroupPrincipal, etc. uses behind the scenes anyway), which I find is much faster. But I did it in C#. It can of course be translated to VB.NET: Find all the members of a group