Showing posts with label UserPrincipalName. Show all posts
Showing posts with label UserPrincipalName. Show all posts

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))}            
 }