Script Repository


Remove user from Microsoft 365 distribution lists

February 16, 2021
6696

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 )
No results found.
Leave a comment

Related Scripts