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

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


$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


	Remove-Variable * -ErrorAction SilentlyContinue

This Post Has 4 Comments

  1. MT

    Thank you so much for this!!!! I’ve been looking for a script or guidance on how to write one that works, stumbled across your script. Thank you!

    1. Pavel Bludov

      You are very welcome!

  2. Alex B.

    Excellent script! if I am on an Exchange Hybrid environment do you know if this will then work on all distro lists since with Hybrid we are synchronized with the cloud? If you could let me know your thoughts that would be appreciated. Thank you.

Leave a Reply