private/removeOrphanSIDs.ps1

function removeOrphanSIDs {
    $domainFacts = get-addomain
    $DOMAINSID = $domainFacts.domainSID.toString()
    $basePath = $domainFacts.DistinguishedName
    $indent = " |--> "

    get-childItem -path "AD:$basePath" -recurse | where-object {$_.objectClass -like "organizationalUnit"} | foreach-object {
        $path = $_
        $ACL = get-acl -path "AD:$path"
        $OrphanList = $ACL.access | where-object {$_.identityReference -like "$DOMAINSID*" -and $_.isInherited -eq $false}
        if ($orphanList) {
            write-host "-> $path"
            $orphanList | foreach-object {
                $identity = $_.identityReference.value.toString()
                #Double-check that this object really does not exist
                $thisObject = get-adobject -filter "objectSID -eq '$identity' -or samaccountName -eq '$identity'"
                if ( $thisObject) {
                    Write-host ("{0}{1,-10} {2,-48} : {3}" -f  $indent, "Orphan: ", $identity, $_.ActiveDirectoryRights)
                    $ACL.removeAccessRuleSpecific($_)
                }
            }
            #now set the ACL
            set-ACL -path "AD:$Path" -AclObject $ACL
        }
    }
}