Home > Enterprise >  remove terminated users from DISTRIBUTION groups in AD
remove terminated users from DISTRIBUTION groups in AD

Time:10-08

I am working on a solution that will help keep our Active Directory clean, so I want to use a Powershell script that will remove the disabled accounts from all groups. I got the following script:

foreach ($username in (Get-ADUser -SearchBase "OU=Terminated Users,DC=corp,DC=company,DC=com" -filter *)) {

    # Get all group memberships
    $groups = get-adprincipalgroupmembership $username;
    
    # Loop through each group
    foreach ($group in $groups) {
    
        # Exclude Domain Users group
        if ($group.name -ne "domain users") {
    
            # Remove user from group
            remove-adgroupmember -Identity $group.name -Member $username.SamAccountName -Confirm:$false;
    
            # Write progress to screen
            write-host "removed" $username "from" $group.name;
    
            # Define and save group names into filename in c:\temp
            $grouplogfile = "c:\temp\"   $username.SamAccountName   ".txt";
            $group.name >> $grouplogfile
        }
    
    }
}

It's working fine but only for security groups. Users are not deleted from distribution groups. I searched the Internet and people mostly suggest to use "Remove DistributionGroup Member" cmdlet. However, this is the Exchange cmdlet and we use Google Workspace for our email, so this cmdlet is not recognized when I run it on the DC.

Any idea how to solve it? Thanks!

CodePudding user response:

@Toni thank you for your help!

I confirm that using "Remove-ADPrincipalGroupMembership" does the job (checked on one user and one group) but I'm having trouble using your script. I only modified it with the search base (I really don't want the script to touch all OUs, at least for now). When I run it, Powershell displays the whole script on the screen, then throws the errors. screenshot

: Failed to remove user: CN=top_man,OU=test_piotr,DC=corp,DC=company,DC=com.samaccountname from groups: - Exception: A parameter cannot be found that matches parameter name 'Members'. CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

Can you please check the script below and let me know if you find any typo?

#get all disabled users, you may limit the scope again on a OU - the current command will get all disabled users regardless where they are located
$disabledUsers = Get-ADUser -SearchBase "OU=test_piotr,DC=corp,DC=company,DC=com" -Properties memberof,samaccountname -filter *

#Loop through array and remove groupmembership and store operation result in $result
$result = @(
    foreach ($user in $disabledusers){ 
        try {
            #Remove all memberships the user has currently, no need to exclude domain users as $user.memberof does not return it
            $null = Remove-ADPrincipalGroupMembership -Identity $user.samaccountname -Members $user.memberof -Confirm:$false -ErrorAction:stop
            write-host "Removed user: $user.samaccountname from groups: $($user.memberof -join ',')"
            #Build object for logfile, you could also loop through $user.memberof to create one object per removed group
            $attrsHt = @{
                smaccountname=$user.samaccountname
                group=($user.memberof -join ',')
                status='removed'
                exception=$null
            }
            New-Object -typename psobject -Property $attrht
        }
        Catch {
            write-error "Failed to remove user: $user.samaccountname from groups: $($user.memberof -join ',') - Exception: $_"
            $attrsHt = @{
                smaccountname=$user.samaccountname
                group=($user.memberof -join ',')
                status='error'
                exception=$_
            }
            New-Object -typename psobject -Property $attrht
        }
    }
)

#export result to file
$result | export-csv "c:\temp\results.csv" -delimiter ';'

CodePudding user response:

The cmdlet Remove-ADPrincipalGroupMembership will help:

#get all disabled users in specified OU
$disabledUsers = get-aduser -SearchBase "OU=test_piotr,DC=corp,DC=company,DC=com" -LDAPFilter '(userAccountControl:1.2.840.113556.1.4.803:=2)' -Properties memberof,samaccountname

#Loop through array and remove groupmembership and store operation result in $result
$result = @(
    foreach ($user in $disabledusers){ 
        try {
            #Only process user account if memberships are present
            If ($user.memberof){
                #Remove all memberships the user has currently, no need to exclude domain users as $user.memberof does not return it
                $null = Remove-ADPrincipalGroupMembership -Identity $user.samaccountname -MemberOf $user.memberof -Confirm:$false -ErrorAction:stop
                write-host "Removed user: $($user.samaccountname) from groups: $($user.memberof -join ',')"
                #Build object for logfile, you could also loop through $user.memberof to create one object per removed group
                $attrsHt = @{
                    smaccountname=$user.samaccountname
                    group=($user.memberof -join ',')
                    status='removed'
                    exception=$null
                }
                New-Object -typename psobject -Property $attrht
            }
        }
        Catch {
            write-error "Failed to remove user: $($user.samaccountname) from groups: $($user.memberof -join ',') - Exception: $_"
            $attrsHt = @{
                smaccountname=$user.samaccountname
                group=($user.memberof -join ',')
                status='error'
                exception=$_
            }
            New-Object -typename psobject -Property $attrht
        }
    }
)
  • Related