# 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 users in the tenant $users = Get-Mailbox -ResultSize Unlimited # Iterate through each user and change the primary username foreach ($user in $users) { $currentPrimary = $user.PrimarySmtpAddress.ToString() $newPrimary = $currentPrimary.Replace($sourceDomain, $targetDomain) if ($newPrimary -ne $currentPrimary) { Write-Host "Changing primary username for user: $($user.UserPrincipalName)" Set-Mailbox -Identity $user.UserPrincipalName -WindowsEmailAddress $newPrimary -EmailAddressPolicyEnabled $false } } # Disconnect from Exchange Online Disconnect-ExchangeOnline