PowerShell; Set UPN to match current Email address

If you’re in the process of migrating to or setting up a hybrid relationship with Office 365 SaaS offerings you probably want to simplify the login process for your users. There are a ton of articles and setup guides out there that explain how to set up Azure AD Connect and even AD FS if you need it but one thing that is more difficult to figure out is setting the UPN. The UPN is a logon in the format of an email address instead of the more common domain\username NTLM nomenclature. Office 365 prefers UPN logons and to be honest they’re easier in your on-premises Active Directory as well.

To prevent your users from needing to logon twice in hybrid environments and to make the UPN easier to remember in on-premises authentication it makes sence to set it to match the user’s email address. The script below assumes you have created a csv file of the user accounts that you want to modify. At least one column in that csv needs to be a qualified identity parameter (SamAccount, Distinguished Name, etc.). When you run the script it will ask for the file and then for the name of the column containing the ID parameter. After you’ve provided those, it will loop through the file and set each user’s UPN to match their current email address.

Import-Module ActiveDirectory
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
Start-Transcript -Path "$env.userprofile\documents\upnupdatelog.txt"

Function Get-FileName($initialDirectory)
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV files (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
} #end function Get-FileName

# *** Entry Point to Script ***

$userlist  = Get-FileName  

$idcolumn = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the case sensitive name of the column that contains the employee's account information:","SamAccountName, DN, CN or Name Column", "ID")

$usernames = Import-Csv -Path $userlist | select $idcolumn -ExpandProperty $idcolumn

Foreach ($user in $usernames)
    $address = Get-ADUser -Identity "$user" -Properties proxyAddresses | Select -Expand proxyAddresses | Where {$_ -clike "SMTP:*"}
    $newUPN = $address.SubString(5)
    Set-ADUser $user -UserPrincipalName $newUPN


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s