profile for Hannel on Stack Exchange, a network of free, community-driven Q&A sites
Project Work Hours
Sat & Sun 6am - 9am
Subscribe via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.


Just a little script I put together during the week to update primary email address on a user account that is been synced over to Office 365 (O365) from Active Directory (AD).  It’s not in any way a perfect script but gets the work done. Download script here


.\UpdatePE.ps1 -NewDomain -Address -KeepCurrentPrimary
.\UpdatePE.ps1 -NewDomain -KeepCurrentPrimary
.\UpdatePE.ps1 -NewDomain 
.\UpdatePE.ps1 -NewDomain -Address

Breakdown of script below

#Update Primary Address
#Hannel Hazeley |


#If addres is not specify, get address(es) from text file 
if ($Address -eq $null) 
 $Address = gc .\UpdatePEUsers.txt

#Set timestamp for log file
$timestamp = Get-Date -Format yyyyMMddhhmmss

#Update all email address in address text file
Foreach ($Eaddress in $Address)

#Get user details using UPN
$ADUser = Get-ADUser -filter {userprincipalname -eq $Eaddress} -Properties *
Get-ADuser $ADUser.SamAccountName -Properties EmailAddress,mail,proxyAddresses,UserPrincipalName > .\$timestamp.$Eaddress.txt

#Create new address using current UPN Format
$NewAddress = $ADUser.userprincipalname -replace "@.*","@$newdomain"

#updates information in proxyaddresses string

#Readds old primary as secondary address
If ($KeepCurrentPrimary.IsPresent)

#Set proxyaddress string into a variable 
$NewProxyAddresses = $ADUser.proxyAddresses

#clear proxaddresses on account 
$ADUser | Set-ADUser -Clear proxyaddresses

#Add each address in variable to proxyaddress on account
ForEach ($NewProxyAddress in $NewProxyAddresses)
$ADUser | Set-ADUser -Add @{proxyAddresses="$NewProxyAddress"} 

#Updates other mail attributes on account
$ADUser | Set-ADUser -Replace @{mail="$NewAddress"} 
$ADuser | Set-ADUser -EmailAddress $NewAddress -UserPrincipalName $NewAddress

#Update a log file information of work done
$confirm = Get-ADuser $ADUser.SamAccountName -Properties EmailAddress,mail,proxyAddresses,UserPrincipalName 
$confirm >> .\$timestamp.$Eaddress.txt
$confirm >> .\$newdomain.$timestamp.All.txt

Posted from Vancouver BC 🙂 Nothing like a vacation post.. Enjoy..