Script Repository


Remove user from Office 365 distribution lists

July 15, 2016
2093

You can use the script in Business Rules, Custom Commands and Scheduled Tasks to remove a user from all distribution lists in Office 365. To add it to your rule, command or task, use the Run a program or PowerShell script action.

For information on how to use the script in your deprovisioning process, see Configure User Deprovisioning.
Edit Remove
PowerShell
# Get the user's unique identifier in Office 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user doesn't have an account in Office 365", "Warning")
    return
}

try
{
    # Connect to Exchange Online
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" `
        -Credential $Context.GetOffice365Credential() -Authentication Basic -AllowRedirection
    Import-PSSession $session -AllowClobber -DisableNameChecking
    
    # Get all distribution groups in Office 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
    Remove-PSSession $session
}

Comments ( 0 )
No results found.
Leave a comment