M365

Changing a User’s Username in Office 365 with On-Prem AD

Many people are running Exchange Online and Office 365 running with Synced usernames and password from the On-Premise Active Directory, it works well most of the time but we discovered a problem when we had to rename a user, although they were renamed in our AD and the 0365 Portal details reflected the updated name, their O365 username remained unchanged.

After some calls with Microsoft they advised the change needs to be completed using PowerShell, to do this you’ll first need to install these two applications MS Online Services Sign-In Assistant and the Windows Azure Active Directory Module 

Once those are installed you need run the following commands

  1. $LiveCred = Get-Credential
  2. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic -AllowRedirection
  3. $Import = Import-Pssession $Session -AllowClobber
  4. Import-Module MSOnline -verbose
  5. Connect-MSOLservice -Credential $LiveCred
  6. Set-MsolUserPrincipalName -UserPrincipalName “oldusername@domain.com” -NewUserPrincipalName “newusername@domain.com”

Alternatively I’d done a really basic PowerShell Script that run commands, you just need to enter the old, and new username you’ll also get prompted for an account that has admin rights in O365.  I’m not that great on scripting so I’m sure someone will find a better way to do it!

#First Starting the Log File in the users desktop
$username = [Environment]::Username
$outfile = “C:\Users\$username\Desktop\o365rename.txt”
Start-Transcript -path $outfile -append

#Ask for new username and old username
$copyuser = Read-Host -Prompt “Enter Original Username WITH the full E-Mail address”
$desuser = Read-Host -Prompt “Enter New Username WITH the full E-Mail address”

#Prints On Screen the old and new names.
Write-Host “You Are Changing $copyuser to $desuser”

#This now establishes connection with the Office365 Azure AD – username should be one that has Admin Rights in 365
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic -AllowRedirection
$Import = Import-Pssession $Session -AllowClobber
Import-Module MSOnline -verbose
Connect-MSOLservice -Credential $LiveCred

#Now we enter the command using the variable we go from the first steps
Set-MsolUserPrincipalName -UserPrincipalName “$copyuser” -NewUserPrincipalName “$desuser”

#Now a prompt to confirm its done.
“Process Complete Check Screen or Log file for Errors”

#Now Printing the open sessions.
Get-PSSession
$closesession = Read-Host -Prompt “Enter Session ID to close”

#Now remove the PSSession
Remove-PSSession -Id $closesession

#Stopping the Transcript
Stop-Transcript

Leave a Reply

Your email address will not be published. Required fields are marked *