Exchange Online: Adding a secondary e-mail domain to all users

I thought that I would share with you a simple script that will add an email domain to your users. This script is handy if you for example would like to add contoso.info to your already existing contoso.com environment. If you are using the email address aaron@contoso.com you want the script to automatically add aaron@contoso.info.

Please note that the domain name that you are adding first has to be added and verified in your Office 365 tenant.

DirSync version (modifying Active Directory using ADSI):

$activeDomain = New-Object DirectoryServices.DirectoryEntry
$domain = $activeDomain.distinguishedName
$searcher = [System.DirectoryServices.DirectorySearcher]"[adsi]LDAP://$domain"
$searcher.filter = '(proxyaddresses=*@contoso.com*)'
$result = $searcher.findall()
$users = $result.Path

$users | ForEach-Object {
    $user = [adsi]"$_"
    $proxyaddresses = $user.proxyaddresses.Value | Where-Object { $_ -like 'smtp:*@contoso.com' }
    foreach ($proxyaddress in $proxyaddresses) {
        $newaddress = ($proxyaddress.split ':')[1] -replace '@contoso.com', '@contoso.info'
        $user.proxyaddresses.add("smtp:$newaddress")
    }
    $user.setinfo()
}

Cloud version:

$cred = Get-Credential -Message 'Please enter your Office 365 admin crendentials'
$O365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/powershell-liveid/' -Credential $cred -Authentication Basic -AllowRedirection 
$importcmd = Import-PSSession $O365 -CommandName @('Get-Mailbox','Set-Mailbox') -AllowClobber

Get-Mailbox -ResultSize Unlimited -Filter { EmailAddresses -like '*@contoso.com' } | Select-Object Identity,EmailAddresses | ForEach-Object {
    $proxyaddresses = $_.EmailAddresses | Where-Object { $_ -like 'smtp:*@contoso.com' }
    foreach ($proxyaddress in $proxyaddresses) {
        $newaddress = ($proxyaddress -split ':')[1] -replace '@contoso.com','@contoso.info'
        Set-Mailbox -Identity $_.Identity -EmailAddresses @{Add="smtp:$newaddress"}    
    }
}

/ Andreas

Advertisements

2 thoughts on “Exchange Online: Adding a secondary e-mail domain to all users

  1. jokinau

    Thank you, that was still useful! I had to fix some sintaxis in the “DirSync version” version, though, or it would complain about some bad instruction. Line 12 should read:
    $newaddress = ($proxyaddress -split ‘:’)[1] -replace ‘@contoso.com’, ‘@contoso.info’
    That fixed it, and it changed all our 100 accounts properly. Thank you again!

Comments are closed.