Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LudovicOmarini/ce55fade0f51cac889d9ba69e1f0f02c to your computer and use it in GitHub Desktop.
Save LudovicOmarini/ce55fade0f51cac889d9ba69e1f0f02c to your computer and use it in GitHub Desktop.
Change the domain of all office 365 users on your tenant.
<#
.SYNOPSIS
Change domain of all office 365 users.
.DESCRIPTION
This script change the domain of all office 365 users on your tenant.
This change the "userPricipalName".
.WARNING
This script assumes you are already connected to the right services and have all modules installed.
.EXAMPLE
Execute the script and type your choices.
.\Change_Domain_userPrincipalName_O365.ps1
#>
#Connect to O365
Connect-MgGraph -Scopes User.ReadWrite.All
#Write here your domains (for example the "onmicrosoft.com" domain on the $WrongDomain)
$GoodDomain="goodcontoso.com"
$WrongDomain="wrongcontoso.com"
#Get all users with the wrong domain
[array]$Users = Get-MgUser -All -Filter "endsWith(userPrincipalName,'$WrongDomain')" -ConsistencyLevel eventual -CountVariable countVar -Sort userPrincipalName
$i = 0
#Update all users with the wrong dromain by the good one
ForEach($User in $Users){
$CurrentUser = $Users[$i].UserPrincipalName.Split("@")[0]
Update-MgUser -UserId $CurrentUser@$BadDomain -UserPrincipalName $CurrentUser@$GoodDomain
$i = $i + 1
}
Write-Host -ForegroundColor Cyan "$i Utilisateurs ont été concerné par le changement de domaine."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment