Script Repository


Copy membership in distribution lists between Microsoft 365 users

June 23, 2020
1804

The script copies membership of a user in Microsoft 365 (Office 365) distribution lists to the current user. The source mailbox is specified via a certain property of the user account. To enable users to select a target mailbox in Active Directory, the property must support the DN syntax. For example, you can use Assistant, Secretary or See Also.

The script must be executed by a Business Rule triggered after modifying the property. Sample Business Rule:

Parameter:

  • $sourceUserDNAttribute - Specifies the LDAP name of the property that is used to store the source user.
Edit Remove
PowerShell
$sourceUserDNAttribute = "assistant" # TODO: modify me

# Get source mailbox DN
try
{
    $sourceUserDN = $Context.TargetObject.Get($sourceUserDNAttribute)
}
catch
{
    $Context.LogMessage("Source user not specified", "Warning")
    return
}

# Get Microsoft 365 Object ID's
$sourceUser = $Context.BindToObjectByDN($sourceUserDN)
try
{
    $sourceUserObjectId = [Guid]$sourceUser.Get("adm-O365ObjectId")
}
catch
{
    $Context.LogMessage("The source user doesn't have a Microsoft 365 account", "Warning")
    return
}

try
{
    $targetUserObjectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    $Context.LogMessage("This user doesn't have a Microsoft 365 account", "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 -CommandName "Get-DistributionGroup", "Get-DistributionGroupMember", "Add-DistributionGroupMember"
    
    # Get all distribution groups in Microsoft 365
    $groups = Get-DistributionGroup -ResultSize unlimited
    foreach ($group in $groups)
    {
        if ($group.IsDirSynced)
        {
            continue
        }
        
        # Skip a group if the source user is not a member
        if (!(Get-DistributionGroupMember $group.Identity | Where{$_.ExternalDirectoryObjectId -eq $sourceUserObjectId.ToString()}))
        {
            continue
        }
        
        try
        {
            # Add target the user
            Add-DistributionGroupMember $group.Identity -Member $targetUserObjectId.ToString() -Confirm:$False -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("Cannot add the target user to 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