Script to remove a user from all distribution groups managed in the cloud

0

The purpose of this PowerShell script is to remove a user from all distribution groups. The script is interactive, it will show the list of groups first, then you have an option to process your request.

While the same can be done using Exchange Admin or Microsoft 365 Admin Center, it is much faster using PowerShell.

Note, the script only processes those distribution groups that are managed in the cloud. If you have some groups synced with Active Directory, those should be processed separately.

$email = Read-Host "Please provide a user's email address to remove from all distribution groups"

$mailbox = Get-Mailbox -Identity $email

$DN=$mailbox.DistinguishedName

$Filter = "Members -like ""$DN"""

$DistributionGroupsList = Get-DistributionGroup -ResultSize Unlimited -Filter $Filter

Write-host `n
Write-host "Listing all Distribution Groups:"
Write-host `n
$DistributionGroupsList | ft

$answer = Read-Host "Would you like to proceed and remove $email from all distribution groups ( y / n )?" 

While ("y","n" -notcontains $answer) {
	$answer = Read-Host "Would you like to proceed and remove $email from all distribution groups ( y / n )?"
	}

If ($answer -eq 'y') {

	ForEach ($item in $DistributionGroupsList) {
		Remove-DistributionGroupMember -Identity $item.DisplayName –Member $email –BypassSecurityGroupManagerCheck -Confirm:$false
	}
	
	Write-host `n
	Write-host "Successfully removed"

	Remove-Variable * -ErrorAction SilentlyContinue
	}

Else

	{
	Remove-Variable * -ErrorAction SilentlyContinue
	}
0

Leave a Reply

Close Menu