Get All Group Users
Retrieves all user accounts that are direct or recursive members of a specific Active Directory group.
- Uses DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity to locate the group in Active Directory.
- Retrieves all members of the group recursively using group.GetMembers(True).
- Only DirectoryServices.AccountManagement.UserPrincipal objects are added to the returned list; other types of members are ignored.
VB
Public Function adGetAllGroupUsers(groupDN As String,
domain As String,
username As String,
password As String) As List(Of UserPrincipal)
' Initialize the list to hold user principals
Dim userList As New List(Of UserPrincipal)()
' Validate inputs
If String.IsNullOrEmpty(groupDN) OrElse
String.IsNullOrEmpty(domain) OrElse
String.IsNullOrEmpty(username) OrElse
String.IsNullOrEmpty(password) Then
Throw New ArgumentException("All parameters must be provided and not empty.")
End If
' Create the PrincipalContext to connect to the domain with ADWS
Dim context As New PrincipalContext(ContextType.Domain, domain, username, password)
Try
' Find the group by its distinguishedName
Dim group As GroupPrincipal =
GroupPrincipal.FindByIdentity(context,
IdentityType.DistinguishedName, groupDN)
If group Is Nothing Then
Throw New Exception("Group not found: " & groupDN)
End If
' Iterate over all members of the group (ADWS handles paging internally)
For Each principal As Principal In group.GetMembers(True) ' True = recursive members
' Filter only user principals
If TypeOf principal Is UserPrincipal Then
userList.Add(CType(principal, UserPrincipal))
End If
Next
Catch ex As Exception
Throw New Exception("Error during ADWS query: " & ex.Message)
End Try
' Return the list of user principals
Return userList
End Function