We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script Repository

Remove user from Microsoft 365 distribution lists

The script removes a user from all distribution lists in Microsoft 365 (Office 365). You can use the script in business rules, custom commands and scheduled tasks configured for the User object type.

Edit Remove
PowerShell
# Get the user's unique identifier in Microsoft 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user doesn't have an account in Microsoft 365", "Warning")
    return
}

try
{
    # Connect to Exchange Online
    $session = $Context.CloudServices.CreateExchangeOnlinePSSession()
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName "Get-DistributionGroup", "Get-DistributionGroupMember", "Remove-DistributionGroupMember"
    
    # Get all distribution groups in Microsoft 365
    $groups = Get-DistributionGroup -ResultSize unlimited
    foreach ($group in $groups)
    {
        # Skip a group if the user is not a member
        if (!(Get-DistributionGroupMember $group.Identity | Where{$_.ExternalDirectoryObjectId -eq $objectID}))
        {
            continue
        }
        
        try
        {
            # Remove the user
            Remove-DistributionGroupMember $group.Identity -Member $objectId -Confirm:$False -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("Cannot remove the user from group $($group.Identity). Error message: " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession $session }
}
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers