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.

Archives

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

Syntax:

.\UpdatePE.ps1 -NewDomain azure.hazelnest.com -Address hhazeley@o365.hazelnest.com -KeepCurrentPrimary
.\UpdatePE.ps1 -NewDomain azure.hazelnest.com -KeepCurrentPrimary
.\UpdatePE.ps1 -NewDomain azure.hazelnest.com 
.\UpdatePE.ps1 -NewDomain azure.hazelnest.com -Address hhazeley@o365.hazelnest.com

Breakdown of script below

#Update Primary Address
#Hannel Hazeley | hhazeley@outlook.com


[cmdletbinding()]
param(
 [Parameter(Mandatory=$true)]
 $NewDomain,
 $Address,
 [Switch]$KeepCurrentPrimary
 )


#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
$ADUser.proxyAddresses.Remove("SMTP:$Eaddress")
$ADUser.proxyAddresses.Remove("smtp:$NewAddress")
$ADUser.proxyAddresses.Add("SMTP:$NewAddress")

#Readds old primary as secondary address
If ($KeepCurrentPrimary.IsPresent)
{
$ADUser.proxyAddresses.Add("smtp:$Eaddress")
}

#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
$confirm >> .\$timestamp.$Eaddress.txt
$confirm >> .\$newdomain.$timestamp.All.txt
}

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