Thursday, November 23, 2017

Change UPN Script for Azure AD Operations

In a lot of Azure deployments, synchronizing identity plays a key part of the overall delivery.  This allows one to utilize on-premises accounts/passwords/etc when logging into Azure, and makes overall management easier.

In some client cases, their internal active directory structure might utilize a domain name that is not routeable on the internet.  This poses a problem, particularly with office 365 integration.  Clients want to log in with their .com address, lets say, but AD Connect ends up syncing a .local address instead.

The fix to this can be quite simple, and generally involves setting the user UPN to the correct external address.  Doing this on an existing domain can be a little painful.  There are some scripts out there that do this, but I wanted to write my own and include some powershell features such as -whatif.

Here is the script, enjoy!

    [Parameter(Mandatory=$true,HelpMessage="The old suffix to look for")]
    [Parameter(Mandatory=$true,HelpMessage="The new suffix to set")]
    [Parameter(Mandatory=$true,HelpMessage="The ou to filter for")]
    [Parameter(Mandatory=$true,HelpMessage="The server to target")]

Import-Module ActiveDirectory 
"Oldsuffix: $oldSuffix"
"Newsuffix: $newSuffix"
"ou: $ou"
"server: $server"

$users = Get-AdUser -Filter "*" -SearchBase "$ou"

if (-not $users){
    "Found no users with specified filter"

foreach ($user in $users){
    "===== Processing {0}" -f $user.UserPrincipalName
    if (-not ($user.UserPrincipalName -like ("*$oldSuffix"))){
        "Users UPN suffix does not match oldsuffix, skipping.."

    if ($user.UserPrincipalName -like ("*$newSuffix")){
        "User is already set correctly, skipping..."
    if ($PSCmdlet.ShouldProcess("Updating user")){
        $newUpn = $user.UserPrincipalName.Replace($oldSuffix,$newSuffix)
        $user | Set-ADUser -server $server -UserPrincipalName $newUpn
        "Changed suffix"
    } else {
        "Would have replaced suffix"