Need PowerShell Script - Swap two domains

I have been now searching for a script that would switch primary email between two domains, using Office 365 Exchange online
each user has a primary and alias email attached to his account, - is primary - is alias
i wish to switch and make the primary and the A as alias
been trying to find and it seems simple, but yeah i would need help :slight_smile:

i will add a few more points that were done before.
The tenant has 3 domains: A, B, C, i only focused on users with A mad B
I followed this guide -
and added the B domain to A domain users, (this did not create a SIP btw, is there another script for this as well?)
Before and after the guide

example: i had 2 domains with their own users, no aliases shared

After the guide and Added a new domain with user names to, so it looks like this +

in the guide above i managed to create a filter, like this
#Get the list of mailboxes in the Office 365 tenant
$Mailboxes = @(Get-Mailbox -Filter { WindowsEmailAddress -like “*” })

so when the script executed it did it all just for these users, was not affected.
now what needs to be done is switching the main / primary domain for the users as explained in the first part.
Let me know if i can add more details, i found a lot of scripts but the mostly add new things or do some other changes, all i need to make the switch between alias and primary,


I believe you are just trying to change the UPN right?

If so something like this should work, where upns.txt is a text file with the usernames of accounts to be changed

$oldsuffix = ""

$newsuffix = ""

gc C:\scripts\upns.txt | Get-ADUser | ForEach-Object {


$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)


$_ | Set-ADUser -UserPrincipalName $newUpn




So for me lets say it would look something like this


$oldsuffix = “

$newsuffix = “

gc C:\scripts\upns.txt | Get-ADUser | ForEach-Object {

$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)

$_ | Set-ADUser -UserPrincipalName $newUpn



and the content of the text file would be







Yep, that should work :wink:

Try against a few test accounts first though!

Since i am new to powershell, this would be a script file that is calling the text file right? also i just came across this link and i think it might fit the requirement



There is a lot of code on that page, you need be more specific.

Which specific attribute(s) in AD are you trying to update.

ok here is what i will do next

i will add a rename to a few users example = >

and then i will also make as the primary email

and i will also have to switch all the other users to be primary email

so for some i will do a rename and for some i will switch from =>