开发者

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).Na开发者_Go百科me.Remove(0, 3))
    Next
End Sub


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


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").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜