Get All Users in an Active Directory Group
- by Matt Hanson
I'm using the following code sample to get a list of all users in a specified AD group (in this case, all users in the "Domain Users" group). My listed code works great, with one exception: it won't return users who have their primary group set to "Domain Users". How can I get a list of all users in the group, including those who have it set as their primary group?
Private Sub GetUsers()
Dim groupSearcher As New DirectorySearcher
Dim groupSearchRoot As New DirectoryEntry("LDAP://OU=Users,DC=domain,DC=com")
With groupSearcher
.SearchRoot = groupSearchRoot
.Filter = "(&(ObjectClass=Group)(CN=Domain Users))"
End With
Dim members As Object
members = groupSearcher.FindOne.GetDirectoryEntry.Invoke("Members", Nothing)
For Each member As Object In CType(members, IEnumerable)
Console.WriteLine(New DirectoryEntry(member).Name.Remove(0, 3))
Next
End Sub