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.
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
}
# Connect to Exchange Online
$Context.CloudServices.ConnectExchangeOnline()
# 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")
}
}