Nothing fancy here. For a given set of usernames, show me the common groups that they are *all* in.
EG; if I have a list of 20 usernames, I need to check all of their group memberships and find the common thread(s) that run between every user.
There are probably a dozen of ways to do this, but when presented with this task, my thoughts immediately went to “if I have a list of every users groups in one single list, for a group to be in common it must appear exactly the same number of times, as there are users being compared”.
Which turned into this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#Define array of usernames $users = @("294808","296165","298287","296058","276710","25824","273156","277568","294933"); #Define list to hold all group names found $groups = @(); # Loop through each username foreach ($user in $users) { # get the users group memberships $usergroups = get-adprincipalgroupmembership $user # Append the list of groups names to the master group list $groups = $groups + $usergroups.name; } # Group and count occurrences of each group name where the count matches the number of users $groups | group-object | where {$_.count -eq $users.count} | sort name | select name |
Or, if your your source list of users needed to come from a get-aduser query:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Get list of users from AD $users = get-aduser -filter {samaccountname -like "*admin*"}; #Define list to hold all group names found $groups = @(); # Loop through each username foreach ($user in $users) { # get the users group memberships $usergroups = get-adprincipalgroupmembership $user.samaccountname # Append the list of groups names to the master group list $groups = $groups + $usergroups.name; } # Group and count occurrences of each group name where the count matches the number of users $groups | group-object | where {$_.count -eq $users.count} | sort name | select name |