Script Repository


Add user to Office 365 distribution groups based on Business Unit membership

December 13, 2017
2307

The script adds a user to Office 365 distribution groups based on the Business Units the user is a member of.

Note: The script uses the $Context variable available on the server side only. This means that the script can be executed only by Business Rules, Custom Commands, and Scheduled Tasks. For example, to schedule Office 365 group membership management, you can create a Scheduled Task configured for the User object type.

Parameter:

  • $groupInfos - specifies names of the Business Units a user needs to be a member of to be added to Office 365 distribution groups and names of the groups that correspond to each Business Unit. A Business Unit can have one or more associated Office 365 groups.
Edit Remove
PowerShell
$groupInfos = @{
    "Business Unit 1" = @("MyGroup1", "MyGroup2");
    "Business Unit 2" = @("MyGroup3");
} # TODO: modify me

# Get the user's unique identifier in Office 365
try
{
    $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    $Context.LogMessage("The user doesn't have an account in Office 365", "Warning")
    return
}
 
# Get Business Units user is a member of
try
{
    $businessUnitDNs = $Context.TargetObject.GetEx("adm-MemberOfBusinessUnits")
}
catch
{
    return # The user is not a member of any Business Units
}
 
# Build a list of groups to add the user to
$groupsToAdd = New-Object "System.Collections.Generic.HashSet[String]"
foreach ($dn in $businessUnitDNs)
{
    $unitDN = New-Object "Softerra.Adaxes.Ldap.DN" $dn
    $unitName = $unitDN.Leaf.Value
   
    $groupNames = $groupInfos[$unitName]
    if ($groupNames -eq $NULL)
    {
        continue
    }
   
    $groupNames | %%{[void]$groupsToAdd.Add($_)}
}
 
if ($groupsToAdd.Count -eq 0)
{
    return # No need to update group membership
}
 
try
{
    # Connect to Exchange Online
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Context.GetOffice365Credential() -Authentication Basic -AllowRedirection
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName "Add-DistributionGroupMember"
   
    # Add user to groups
    foreach ($groupName in $groupsToAdd)
    {
        try
        {
            Add-DistributionGroupMember $groupName -Member $objectId.ToString() -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when adding the user to $groupName group. Error: " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    if ($session) { Remove-PSSession $session }
}


Comments ( 0 )
No results found.
Leave a comment