# Connect to Exchange Online $credential = Get-Credential Connect-ExchangeOnline -Credential $credential # Define the source and target domain $sourceDomain = "olddomain.com" $targetDomain = "newdomain.com" # Get all groups in the tenant $groups = Get-UnifiedGroup -ResultSize Unlimited # Iterate through each group and change the email address foreach ($group in $groups) { $currentPrimary = $group.PrimarySmtpAddress.ToString() $newPrimary = $currentPrimary.Replace($sourceDomain, $targetDomain) if ($newPrimary -ne $currentPrimary) { Write-Host "Changing email address for group: $($group.DisplayName)" # Change the email address for the group Set-UnifiedGroup -Identity $group.Identity -PrimarySmtpAddress $newPrimary # Change the email address for the group's underlying mailbox (if applicable) if ($group.RecipientTypeDetails -eq "GroupMailbox") { Set-Mailbox -Identity $group.PrimarySmtpAddress -WindowsEmailAddress $newPrimary } # Change the email address for any associated distribution lists (if applicable) $distributionLists = Get-DistributionGroup -RecipientTypeDetails MailUniversalDistributionGroup, MailUniversalSecurityGroup -LinkedGroup $group.Identity -ResultSize Unlimited foreach ($distributionList in $distributionLists) { Set-DistributionGroup -Identity $distributionList.Identity -PrimarySmtpAddress $newPrimary } } } # Disconnect from Exchange Online Disconnect-ExchangeOnline