Power-Shell script to do changes of UPNs for all users

      Comments Off on Power-Shell script to do changes of UPNs for all users

The following example PowerShell script to do changes of 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