powershell - Remove all "ForeignSecurityPrincipals" from AD Groups selected by SID

457 views Asked by At

Following situation: You have ForeignSecurityPrincipals in your AD Groups. But Remove-ADGroupMember cannot remove them, since it does not support removing "ForeignSecurityPrincipal". Using the DOMAIN\SamAccountName Method is not available as well, since that old domain does not exist any more. On top you are not allowed to use external modules since that company does not want external modules.

1

There are 1 answers

0
Joachim Otahal On

I needed this functionality today for a mass-cleanup job, as written without needing extra modules, and without having the old AD available since it was already killed. Found nothing, so I developed this solution and share it. You have to get the DOMAINSID first, which should be simple. My example uses -Server since the "adminforest" is not the same as the forest of the groups to be modified. It searches all groups from the given OU, selects all groups with members matching the DOMAINSID, and then removes each member matching the DOMAINSID from those groups. Don't forget to set $WhatIf=$false, else it runs in "we test only" mode.

$Groups = Get-ADGroup -Server other.domain.local -Filter * -SearchBase "OU=Groups,OU=SubOU,OU=Subsidary,DC=OTHER,DC=DOMAIN,DC=LOCAL" -Properties *
$GroupsWithForeignMembers = @($Groups.Where({$_.member -like "*S-1-5-21-2631234548-991234592-3812345124*"}))
$WhatIf=$true
foreach ($Group in $GroupsWithForeignMembers) {
    $MemberForeign= @((Get-ADGroup -Server bk.bwl.net -Identity $Group.SamAccountName -Properties member).member.Where({$_ -like "*S-1-5-21-2631234548-991234592-3812345124*"}))
    foreach ($Member in $MemberForeign) {
        "Removing $Member from $($Group.SamAccountName)" | Tee-Object -Append "GROUPS-cleanup.log"
        Set-ADObject -Server other.domain.local -Identity $Group -Remove @{member=$Member} -Verbose -WhatIf:$WhatIf
    }
}