Script Repository


Create distribution list in Microsoft 365

April 28, 2020
3172

The script creates a distribution list in Microsoft 365 (Office 365) based on an Active Directory group object. It also copies the memberships of the AD group and assigns the group owner in Microsoft 365 (Office 365).

To automatically create Microsoft 365 (Office 365) groups after AD group creation, create a Business Rule that runs the script after creating a new group. Also, you can create a Custom Command to create Microsoft 365 (Office 365) groups manually or a Scheduled Task to synchronize AD groups to Microsoft 365 (Office 365) on a certain schedule.

Edit Remove
PowerShell
# Get group members

try
{
    $memberGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMembersGuid")
}
catch
{
    $memberGuidsBytes = @()
}

# Get members IDs in Microsoft 365
$m365memberIds = @{}
foreach ($guidBytes in $memberGuidsBytes)
{
    $path = "Adaxes://<GUID=" + [Guid]$guidBytes + ">"
    $member = $Context.BindToObject($path)
    
    # Get Microsoft 365 ID
    try
    {
        $objectId = ([Guid]$member.Get("adm-O365ObjectId")).ToString()
    }
    catch
    {
        continue
    }
    
    $memberName = $member.Get("name")
    $m365memberIds.Add($objectId, $memberName)
}

# Get group owner
try
{
    $ownerDN = $Context.TargetObject.Get("managedBy")
    $owner = $Context.BindToObjectByDN($ownerDN)
    $ownerId = ([Guid]$owner.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $ownerId = $NULL
}

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
    
    # Check if group already exists
    $group = Get-DistributionGroup -Identity "%name%" -ErrorAction SilentlyContinue
    
    if ($group -eq $NULL)
    {
        # Create the group in Microsoft 365 and Exchange Online
        try
        {
            $group = New-DistributionGroup -Name "%name%" -Type Distribution -Members @($m365memberIds.Keys) -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when creating the group in Microsoft 365. Error: " + $_.Exception.Message, "Warning")
            return
        }
    }
    else
    {
        $currentGroupMembers = Get-DistributionGroupMember -Identity $group.Id
        if ($currentGroupMembers -ne $NULL)
        {
            foreach ($member in $currentGroupMembers)
            {
                if ($m365memberIds.ContainsKey($member.ExternalDirectoryObjectId))
                {
                    $m365memberIds.Remove($member.ExternalDirectoryObjectId)
                    continue
                }
                
                # Remove member
                try
                {
                    Remove-DistributionGroupMember -Identity $group.Id -Member $member.ExternalDirectoryObjectId -ErrorAction Stop -Confirm:$False
                }
                catch
                {
                    $Context.LogMessage("An error occurred when removing member '$($member.Id)' from the Microsoft 365 group. Error: " + $_.Exception.Message, "Warning")
                    continue
                }
            }
        }
        
        foreach ($id in $m365memberIds.Keys)
        {
            try
            {
                Add-DistributionGroupMember -Identity $group.Id -Member $id -ErrorAction Stop
            }
            catch
            {
                $Context.LogMessage("An error occurred when adding member '$id' to the Microsoft 365 group. Error: " + $_.Exception.Message, "Warning")
                continue
            }
        }
    }
    
    # Assign the owner
    if ($ownerId -ne $NULL)
    {
        try
        {
            Set-DistributionGroup -Identity $group.Id -ManagedBy $ownerID -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when updating the distribution group. Error: " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    if ($session) { Remove-PSSession $session }
}

Comments ( 0 )
No results found.
Leave a comment

Related Scripts