Script Repository


Copy membership in distribution lists between Microsoft 365 users

February 12, 2021
3298

The script copies membership of a user in Microsoft 365 (Office 365) distribution lists to the current user. The source user is stored in the DN property (e.g. Assistant) of the target user. The script must be executed in a business rule triggering after modifying the property.

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 IDs
$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 = $Context.CloudServices.CreateExchangeOnlinePSSession()
    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 group if source user is not member
        if (!(Get-DistributionGroupMember $group.Identity | Where{$_.ExternalDirectoryObjectId -eq $sourceUserObjectId.ToString()}))
        {
            continue
        }
        
        try
        {
            # Add target user to group
            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