Monday, October 8, 2012

Change UserPrincipalName with Script via Powershell

When setting up single sign on in Office 365, one problem you may run into is needing to change the UserPrincipalName to match your public mail domain. For example, if your primary Active Directory Domain is something like @domain.local it will not work with Office 365 and you will need to change the UserPrincipalName to @domain.com.

After you have created the alternate UPN as described in http://techatmount.blogspot.com/2012/09/office-365-single-sign-on-errors.html, you can script the change the of UPN of users to a different UPN using the following powershell script.

I played around with the formatting of the code below to get it nicely color coded. This means that some of the line breaks don't show well here, but a copy and a paste into notepad should format it properly.

Import-Module ActiveDirectory            
$privateUPN = 'domain.local'            
$publicUPN = 'domain.edu'            
Get-ADUser -SearchBase "ou=Students,dc=domain,dc=com" -SearchScope SubTree -filter * |             
ForEach-Object {if ($_.UserPrincipalName){#Checks if the UserPrincipalName is null            
 $newUserName = $_.UserPrincipalName.Replace($privateUPN,$publicUPN) #Changes the UPN and sets the new name to a variable            
 <# The following is to output extra details for troubleshooting  : Note the line continuation is a back tick#>            
 #Write-Host $_.UserPrincipalName " now is " $newUserName -ForegroundColor DarkRed `            
 $_ | Set-ADUser -Server $privateUPN -UserPrincipalName $newUserName <#-WhatIf#>}#The whatif commands doesn't actaully change anything remove it to make the change.            
 else {Write-Host $_.sAMAccountName + " does not have a UPN" -ForegroundColor DarkCyan}            
 #{$newUserName = $_.UserPrincipalName.Replace($privateUPN,$publicUPN))}            
 }


2 comments:

  1. and when you have an on premise exchange server, it likes to try to handle the on-premise mail for any and all of your defined UPNs instead of sending the alternate UPN mail to the cloud.. did you experience that too?

    ReplyDelete
  2. No, We didn't end up experiencing that. All of our mail was already being handled by our on-premise server. Our trouble came trying to get the mail flow working properly because we were trying to use an on-premise barracuda. We ended up just going with FOPE to get it working.

    ReplyDelete