Script Repository


Create distribution list in Office 365

January 30, 2017
1228

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

To automatically create 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 Office 365 groups manually or a Scheduled Task to synchronize AD groups to 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 Office 365
$0365memberIds = @{}
foreach ($guidBytes in $memberGuidsBytes)
{
    $path = "Adaxes://<GUID=" + [Guid]$guidBytes + ">"
    $member = $Context.BindToObject($path)
    
    # Get Office 365 ID
    try
    {
        $objectId = ([Guid]$member.Get("adm-O365ObjectId")).ToString()
    }
    catch
    {
        continue
    }
    
    $memberName = $member.Get("name")
    $0365memberIds.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 Office 365 and Exchange Online
        try
        {
            $group = New-DistributionGroup -Name "%name%" -Type Distribution -Members @($0365memberIds.Keys) -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when creating the group in Office 365. Error: " + $_.Exception.Message, "Warning")
            return
        }
    }
    else
    {
        $currentGroupMembers = Get-DistributionGroupMember -Identity $group.Id
        if ($currentGroupMembers -ne $NULL)
        {
            foreach ($member in $currentGroupMembers)
            {
                if ($0365memberIds.ContainsKey($member.ExternalDirectoryObjectId))
                {
                    $0365memberIds.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 Office 365 group. Error: " + $_.Exception.Message, "Warning")
                    continue
                }
            }
        }
        
        foreach ($id in $0365memberIds.Keys)
        {
            try
            {
                Add-DistributionGroupMember -Identity $group.Id -Member $id -ErrorAction Stop
            }
            catch
            {
                $Context.LogMessage("An error occurred when adding member '$id' to the Office 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