And to share some of the daily use of small scripts ha, for example, some small enterprises in the use of O365 started with the O365 of the domain name, after a period of time to use their own domain name, the administrator will need to change the user's UPN to a custom domain name. In general this is not a complex work, the simple words may be a few lines of code is done, of course, if you want to write a little more normative, then you can add some logic control class statements
param ([Parameter (mandatory = $true)][string] $CustomDomainName, [Parameter (mandatory = $false)][bool] $IncludeGlobalAdmin = $false) function change-userprincipalname{param ([Parameter ( mandatory = $true)][string] $OldUserPrincipalName, [parameter (mandatory = $true)][string]$ Customdomainname) $Error. Clear () try{$Role = get-msoluserrole -userprincipalname $ olduserprincipalname $Change = $trueif ($Role -ne $null) {#Company administratorif ($Role .objectid -eq "62e90394-69f5-4237-9190-012177145e10") {if ($ includeglobaladmin -eq $false) {write-host ("$ (get-date) * found {0} {1}, pass " -f $Role .name, $OldUserPrincipalName) -ForegroundColor ' Yellow ' $Change = $false}} #Directory Synchronization Accountelseif ($Role .objectid -eq " D29b2b05-8046-44ba-8758-1e26182fcf32 ") {write-host ("$ (get-date) * found {0} {1}, pass" -f $Role. name, $ olduserprincipalname) -ForegroundColor ' yellow ' $Change = $false}}if ($Change -eq $true) {$UserName = $OldUserPrincipalName. Split ("@") [0] $NewUserPrincipalName = $ username + "@" + $CustomDomainNameWrite-host ("$ (get-date) * Changing User principal name {0} to {1} " -f $OldUserPrincipalName, $ Newuserprincipalname) -ForegroundColor ' Cyan ' set-msoluserprincipalname -userprincipalname $OldUserPrincipalName -NewUserPrincipalName $NewUserPrincipalName}}catch{write-warning $Error [0 ]. Exception.Message}} $Domains = Get-MsolDomainif ($Domains. Name.tolower (). Contains ($ Customdomainname.tolower ())) {get-msoluser -all | %{change-userprincipalname - Olduserprincipalname $_. Userprincipalname -customdomainname $CustomDomainName}}else{throw "$ (get-date) * Domain Name $CustomDomainName not found in your tenant "}
For global admin, the script added a parameter of type bool to decide whether or not to modify the UPN of the global admin, so that it can be more controllable for the administrator to do this kind of operation.
Bulk modifying the O365 user UPN using PowerShell