When an organization transitions to a new domain, updating the email addresses and aliases for all distribution lists can be a daunting task. This PowerShell script automates the process to replace the old domain with the new domain for all distribution lists in Exchange Online.
Prerequisites
Before running the script, ensure the following:
- Install Exchange Online PowerShell Module: Follow the guide at Install Exchange Online Module.
- Connect to Exchange Online:
Connect-ExchangeOnline -UserPrincipalName <your-admin-email>
PowerShell Script
# Define old and new domains
$oldDomain = "old.com"
$newDomain = "new.com"
# Retrieve all distribution lists
$distributionLists = Get-DistributionGroup
foreach ($dl in $distributionLists) {
$currentPrimaryEmail = $dl.PrimarySmtpAddress.ToString()
# Check if primary email matches the old domain
if ($currentPrimaryEmail -like "*@${oldDomain}") {
# Change primary email domain
$newPrimaryEmail = $currentPrimaryEmail -replace $oldDomain, $newDomain
# Create new alias
$newAlias = $dl.Alias + "@" + $newDomain
try {
# Update primary email
Set-DistributionGroup -Identity $dl.Identity -PrimarySmtpAddress $newPrimaryEmail
# Add new alias
Set-DistributionGroup -Identity $dl.Identity -EmailAddresses @{Add=$newAlias}
Write-Host "Updated DL: $($dl.DisplayName) - New Primary Email: $newPrimaryEmail - New Alias: $newAlias"
}
catch {
Write-Host "Failed to update DL: $($dl.DisplayName) - $($_.Exception.Message)"
}
}
else {
Write-Host "Skipped DL: $($dl.DisplayName) - Primary email does not match old domain."
}
}
Script Breakdown
- Retrieve All Distribution Lists: The script uses
Get-DistributionGroupto fetch all distribution lists in Exchange Online. - Check for Old Domain: The primary email address of each distribution list is checked to see if it matches the old domain.
- Update Primary Email: If the primary email address matches the old domain, it is replaced with the new domain.
- Add Alias: A new alias is created and added to the distribution list.
- Error Handling: Errors during updates are caught and logged.
Notes
- Ensure you have the necessary permissions in Exchange Online to modify distribution lists.
- Test the script in a non-production environment before executing it in production.
- Backup the distribution list configurations if necessary.
By using this script, you can streamline the domain transition process for your distribution lists, saving time and reducing manual effort.