Correcting hybrid routing addresses after updating SAMAccountName

I just recently got into a situation where customer with hybrid Exchange had to change many users SAMAccountName, which led to a whole bunch weird stuff due to hybrid routing addresses. So, quick script here to localize the users with Proxyaddresses that doesn't match the and make sure that they get the correct address.

Remember that I'm no way responsible for what happens if you run this script. You shouldn't run any script you find in a live environment, without knowing what it does.

# Variables, get all users and define your tenantname. Feel free to customize the $users variable to get a more accurate result for your domain
$users = Get-ADUser -Filter * -Properties proxyaddresses -SearchBase "OU=Users,DC=domain,DC=local"
$tenant = "tenantName"

# Now, for each object find...
$users | ForEach-Object {
    ## The correct routing address:
    $routingMail = "smtp:" + $_.samaccountname + "@" + $tenant + ""
    ## The users proxyaddresses
    $proxy = $_.proxyaddresses
    ## Then, if the user doesn't have the correct routing address, either replace the wrong one or just add a new one if there wasn't one
    if ($proxy -notcontains $routingMail) {
        ### First, we find the bad proxyaddresses and make sure we take a not of it
        $proxy | ForEach-Object {
            switch -wildcard ($_) {
                "smtp:*@$tenant.mail.*" { $wrongProxy = $_ }
        ### Then, we try to remove the wrong proxy. If there was no proxy present, this will fail but we'll make sure we don't see any of that nonsense
        Write-host -ForegroundColor Red "Removing $wrongProxy"
        Set-ADUser -Identity $_.SamAccountName -remove @{proxyAddresses=$wrongProxy} -ErrorAction SilentlyContinue
        ### Lastly, we'll add the correct address.
        Write-host -ForegroundColor Green "Adding $routingMail"
        Write-host $routingMail
        Set-ADUser -Identity $_.SamAccountName -add @{proxyAddresses=$routingMail} -ErrorAction SilentlyContinue
Show Comments