27 December 2018

Replace Primary SMTP Address | AD

I've recently had to replace the Primary SMTP address for all users within an organisation.  Of course this is a lot easier if you script it.

I needed to do this as the client was changing their primary address, but wanted to retain all the current proxyAddresses as well.

This was achieved by using two scripts.

$Users = Get-ADUser -SearchBase 'OU=ouname,OU=ouname,OU=ouname,OU=ouname,DC=domai,DC=com,DC=au' -Filter * -Properties mail,ProxyAddresses | Select-Object samaccountname,ProxyAddresses
Foreach ($User in $Users)

            $Samaccountname = $User.samaccountname
            $SMTP = "SMTP:$samaccountname@newdomain.com.au"
            Set-ADUser $samaccountname -Add @{proxyAddresses=$SMTP}

This script adds the new SMTP address for all users within a certain OU.  Of course this will cause some troubles on its own, as there's now going to be two SMTP addresses, marked as primary.

The following script clears this up:

Get-ADUser -SearchBase 'OU=ouname,OU=ouname,OU=ouname,OU=ouname,DC=domai,DC=com,DC=au' -Filter * -Properties mail,ProxyAddresses |
    Foreach {  
        $proxies = $_.ProxyAddresses | 
                $a = $_ -replace 'SMTP','smtp'
                if($a -match 'newdomain.com.au'){
                    $a -replace 'smtp','SMTP'
        $_.ProxyAddresse = $proxies
        Set-ADUser -instance $_



  1. This will remove smtp:firstname.lastname@domain.com and replace it with SMTP:firstname.lastname@domain.com

    [string]$proxydomain = "@Domain.com.au"; #Proxy domain
    [string]$usersOU = "OU=Users,DC=Domain,DC=local"; #OU to apply changes
    [int]$count = 0 ;

    Import-Module ActiveDirectory

    Get-ADUser -Filter "*" -SearchScope Subtree -SearchBase "$usersOU" -Properties proxyAddresses, employeeType, givenName, Surname | foreach-object {

    Write-Host "Editing user: $_.SamAccountName"

    if ($_.Proxyaddresses -match $_.givenName+"."+$_.Surname+$proxydomain)
    Set-ADUser -Identity $_.SamAccountName -remove @{proxyAddresses="smtp:"+$_.givenName+"."+$_.Surname+$proxydomain}
    Write-Host "Removed '$_.SamAccountName' smtp Address"
    Set-ADUser -Identity $_.SamAccountName -add @{proxyAddresses="SMTP:"+$_.givenName+"."+$_.Surname+$proxydomain}
    Write-Host "Result: Added '$_.SamAccountName' Proxy address."

    Write-Host "Nothing Changed."


    Write-Host "Sucessfully Edited" $count "users"

    1. Great, that has done it for me!
      Thank you