Powershell – Changing the UPN in Office 365 for Bulk Users

It is very normal for IT admins to change people’s names, or domain names in Active Directory because they have got married or completed a deed poll, or purchase a new primary domain name. In doing this, the user’s sign-in address so should also reflect the name change. In this post, I am going to look at how to change the User Principal Name for a single user and multiple users.

Setting Up Your PowerShell Environment

First of all you will require the relevant PowerShell Module to connect to Office 365, this can be obtained by running the following cmdlet;

Install-Module MSOnline

Install-Module AzureAD

It might depend on your environment, ask you to install the NuGet provider, as well as installing a module from the PSGallery. Answer Y to both these questions if you encounter them.

Changing a UserPrincipalName for a single user

Using Connect-MSOL Module

Set-MsolUserPrincipalName -UserPrincipalName andrew.moran@contoso.onmicrosoft.com -NewUserPrincipalName andrew.moran@contoso.com

Using AzureAD Module

Set-AzureADUser -ObjectID andrew.moran@contoso.onmicrosoft.com -UserPrincipalName andrew.moran@contoso.com

Changing UserPrincipalName in bulk for users

The following script requires the following in order to be run;

– AzureAD PowerShell Module
– Source CSV file with the following DisplayName,UserPrincipalName,MailNickName

#region Variables
 $Filepath = Get-FileName -initialdirectory "$env:USERNAME\downloads"


 #region Functions
 Function Get-FileName {  
  Add-Type -AssemblyName System.windows.forms | Out-Null
    $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialdirectory
    $OpenFileDialog.filter = "All files (*.*)| *.*"
    $OpenFileDialog.ShowDialog() | Out-Null


# Start-Time
$start = [system.datetime]::Now

# Output will be added to C:\temp folder. Open the Add-SMTP-Address.log with a text editor. For example, Notepad.
Start-Transcript -Path C:\temp\ChangingUPN.log -Append

# Get all mailboxes
$Mailboxes = Import-Csv -Path $FilePath 

# Loop through each mailbox
foreach ($Mailbox in $Mailboxes) {
        # Change @contoso.com to the domain that you want to add
        $Address = "$($Mailbox.MailNickName)@ipfin.co.uk"

        # Remove the -WhatIf parameter after you tested and are sure to add the secondary email addresses
        Set-AzureADUser -ObjectId $Mailbox.MailNickName -UserPrincipalName $Address

        # Write output
        Write-Host "Setting $($Address) to $($Mailbox.UserPrincipalName)" -ForegroundColor Green

    # End-Time
$end = [system.datetime]::Now

$resulttime = $end - $start
Write-Host ('Execution : {0}Days:{1}Hr:{2}Min:{3}Sec' -f $resultTime.Days, $resultTime.Hours, $resultTime.Minutes, $resultTime.Seconds) 

The Author – Blogabout.Cloud