powershellactive-directorymemberget-adusergroup-object

Find multiple of the same objects in an Array and do something with these objects


I need a PowerShell-Script that does the following:

  1. Get the AD-Groupmember of six different AD-Groups.
  2. Show only members who are in more than two of those AD-Groups.
  3. 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 

Solution

  • The following should do the trick, basically create an output having the user's samAccountName and their respective group they're a memberOf. Then that output is piped to Group-Object where the objects are grouped by their samAccountName 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's samAccountName and all the group's DistinguishedName they're a member of.

    $groups = 'AD-Group1', 'AD-Group2', 'AD-Group3', 'AD-Group4', 'AD-Group5', 'AD-Group6'
    $groups | ForEach-Object {
        $dn = (Get-ADGroup $_).DistinguishedName
        # find all recursive user object members of this group
        foreach($member in Get-ADUser -LDAPFilter "(memberOf:1.2.840.113556.1.4.1941:=$dn)") {
            [pscustomobject]@{
                samAccountName = $member.samAccountName
                MemberOf       = $dn
            }
        }
    } | Group-Object samAccountName | Where-Object Count -GT 2