Matt Hanson
Matt Hanson

Reputation: 3504

Get All Users in an Active Directory Group

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

Upvotes: 1

Views: 1439

Answers (2)

Matt Hanson
Matt Hanson

Reputation: 3504

Solution found using DirectoryServices.AccountManagement instead:

For Each group As GroupPrincipal In UserPrincipal.FindByIdentity(New PrincipalContext(ContextType.Domain, "domain.com"), IdentityType.SamAccountName, "userName").GetGroups()
    ' Do something with group name.
Next

Upvotes: 4

DougN
DougN

Reputation: 4617

I'm searching for a robust way to do this too. If you specifically want users that are part of "Domain Admins", query for all users where primaryGroupID=512 (512 is a well-known ID that means "Domain Admins").

Upvotes: 0

Related Questions