Power Shell script changes “All” UPNs at Office 356 Tenant

Now a days I am busy working with Domain & Email services consolidation project and got an opportunity to do Vanity Domain & Mailbox migration between O365 tenant. One of the key step is to migrate the SMTP domain source to target tenant once the cut off window is scheduled and first change all users proxy address to onmicrosoft.com domain before removal of vanity domain from source tenant. Just thought to share the one basic power shell script as mention below.

The following example PowerShell script changes “All” UPNs for all users except the admin account replacing the domain name by the onmicrosoft.com addresses and redirects output to a file UPNChangeOutput.txt:

============================================================================

$UserCredential = Get-Credential

Connect-MsolService -Credential $UserCredential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

Import-PSSession $Session -AllowClobber

$testpath = test-path c:\temp; If ($testpath -eq $false) {new-item -type directory c:\temp}; $dataout = @();

Get-MsolUser -All | ? {$_.UserPrincipalName -match “Sourcedomain.com” -and $_.UserPrincipalName -notmatch “admin”} | % {Set-MsolUserPrincipalName -ObjectId $_.objectId -NewUserPrincipalName ($_.UserPrincipalName.Split(“@”)[0] + “@Sourcedomain.onmicrosoft.com”); $dataout += “$($_.UserPrincipalName)” ; $_.UserPrincipalName };$dataout | out-file c:\temp\UPNChangeOutput.txt

============================================================================

    • In the PowerShell script above, replace @Sourcedomain.onmicrosoft.com with @”yourSourceTenantName”.onmicrosoft.com, where “yourSourceTenantName” is the actual name of the tenant account. This is set when the tenant account was first created.
    • If there are several domains in the Source tenant being moved to the new tenant, the PowerShell script above must be run for each of the domains.
  • From the admin portal, change the UPN of the admin account to the onmicrosoft.com address.
  • Once the script has been run, the domain can be removed. Remove the domain from the admin portal