I need a PowerShell-Script that does the following:
- Get the AD-Groupmember of six different AD-Groups.
- Show only members who are in more than two of those AD-Groups.
- Remove these members from those AD-Groups.
I could only come up with a Script, that finds all members of those six AD-Groups and show them grouped descending from the occurrence in the groups. I don't know how to go from here to automatically remove the members with count 3 or greater from the AD-Groups.
$arrMembersADGroup1 = Get-ADGroupMember -Identity "AD-Group1" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrMembersADGroup2 = Get-ADGroupMember -Identity "AD-Group2" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrMembersADGroup3 = Get-ADGroupMember -Identity "AD-Group3" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrMembersADGroup4 = Get-ADGroupMember -Identity "AD-Group4" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrMembersADGroup5 = Get-ADGroupMember -Identity "AD-Group5" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrMembersADGroup6 = Get-ADGroupMember -Identity "AD-Group6" -Recursive | Get-ADUser -Properties Mail | Select-Object Mail
$arrAllGroupMembers = $arrMembersADGroup1 + $arrMembersADGroup2 + $arrMembersADGroup3 + $arrMembersADGroup4 + $arrMembersADGroup5 + $arrMembersADGroup6
$arrAllGroupMembers | Group-Object -Property Mail -NoElement | Sort-Object -Property count -Descendin | Select-Object Name,count
The following should do the trick, basically create an output having the user's
samAccountName
and their respective group they're amemberOf
. Then that output is piped toGroup-Object
where the objects are grouped by theirsamAccountName
to later be filtered where there are more than 2 grouped objects (meaning, they would be a member of 3 or more groups). The output you should get is the user'ssamAccountName
and all the group'sDistinguishedName
they're a member of.