Back to script library
Entra / Microsoft 365 · Exchange Online

Create dynamic distribution lists from SMTP domains

Stamps primary SMTP addresses into custom attribute 13, then creates a dynamic distribution list for each domain in the organization.

Connect & set up

Run these once per session. All scopes are read-only unless the script makes changes.

Connect-ExchangeOnline -SkipLoadingCmdletHelp

Run it

The main script. Copy it, or download the .ps1 and run it from your console.

If (Get-ConnectionInformation) {
Write-Host "Checking the target shared mailboxes and user accounts to process..."
} Else {
Connect-ExchangeOnline -SkipLoadingCmdletHelp
}
[array]$Domains = "office365itpros.com", "office365exchangebook.com"
$DefaultDDLOwner = "Lotte.Vetler@Office365itpros.com"
[array]$Mbx = Get-ExoMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited `
-Filter {CustomAttribute13 -eq $Null}
If ($Mbx) {
# For each mailbox, find the domain part of the primary SMTP address and store it
[int]$i = 0
ForEach ($M in $Mbx) {
$Domain = $M.PrimarySMTPAddress.Split("@")[1]
If ($M.CustomAttribute13 -ne $Domain) {
Write-Host ("Updating mailbox {0} ({1}/{2})" -f $M.DisplayName, $i, $Mbx.count)
Set-Mailbox -Identity $M.ExternalDirectoryObjectId -CustomAttribute13 $Domain
}
}
} Else {
Write-Host "Can't find any mailboxes - exiting"; break
}
Write-Host "Finished processing mailboxes - now creating dynamic distribution lists"
# Loop through each domain and create a dynamic distribution list (if one doesn't exist already)
ForEach ($D in $Domains) {
$DDLAlias = ("Domain.{0}" -f $D)
If ($Null -eq (Get-DynamicDistributionGroup -Identity $DDLAlias -ErrorAction SilentlyContinue)) {
Write-Host ("Creating dynamic distribution list for the {0} domain..." -f $D) -ForegroundColor Yellow
$Filter = "CustomAttribute13 -eq '$D' -and RecipientTypeDetails -eq 'UserMailbox'"
$DDLName = ("{0} users" -f $D)
$DDLDisplayName = ("People with {0} primary SMTP addresses" -f $D)
$DDLPrimarySMTPAddress = ("{0}@office365itpros.com" -f $DDLAlias)
$DDLMailTip = ("Use this distribution list to send to all users with a {0} email address" -f $D)
# Create the new dynamic distribution list
$DDL = New-DynamicDistributionGroup -Name $DDLName -DisplayName $DDLDisplayName -Alias $DDLAlias `
-PrimarySmtpAddress $DDLPrimarySMTPAddress -RecipientFilter $Filter
If ($DDL) {
Write-Host ("Dynamic distribution list created for {0}" -f $DDLDisplayName)
# Make sure that the dynamic distribution list has an owner
Set-DynamicDistributionGroup -Identity $DDLAlias `
-ManagedBy $DefaultDDLOwner -MailTip $DDLMailTip
}
} Else {
Write-Host ("A dynamic distribution list already exists for {0} users" -f $D) -ForegroundColor Red
}
}
Attribution