Decoding legacy Exchange DN from NDR

Occasionally in Exchange you will accidentally or intentionally recreate a user, or delete some values from their object - this will impact the LegacyExchangeDN value. I have seen this happen where mailuser objects were removed from Office 365, the user objects were cloud only and the LegacyExchangeDN was gone forever.

Contrary to its name, the LegacyExchangeDN value is critical to maintaining active conversations within your organisation. When a user’s legacyExchagneDN is lost, collegues replying to conversations with that user will get an NDR. When they create a new email the email will work.

You can extract the old LegacyExchangeDN from the NDR by finding the string that looks like this IMCEAEX-_O=ExchangeLabs_ou=Exchange+20Administrative+20Group+20+28FYDIBOHF23SPDLT+29_cn=Recipients_cn=wrish+2Eonmicrosoft+2Ecom-53453-Jones+2C+20Martial+20+28dfs9vk29@wrish.com and use the function below to convert it back to an X500 attribute which you add to the proxyaddresses attribute of the user.

Here is the function:

function decode-NDRX500Address ($DN){
    #Generate a list of replacements to be done
    $replacements = @{'^IMCEAEX-'='';'_'='/';'@.+$'=''}
    (0..127) | %{$replacements."\+$('{0:x}' -f $_)" = "$([char]$_)"}
    #Add X500 to the start
    $replacements."^" = "X500:"
    #Perform the replacements
    $replacements.GetEnumerator() | %{
        $dn = $dn -replace $_.key,$_.Value
    }
    $DN
}

Here is how you can use it:

$ValueFromNDR = 'IMCEAEX-_O=ExchangeLabs_ou=Exchange+20Administrative+20Group+20+28FYDIBOHF23SPDLT+29_cn=Recipients_cn=wrish+2Eonmicrosoft+2Ecom-53453-Jones+2C+20Martial+20+28dfs9vk29@wrish.com'
decode-NDRX500Address $ValueFromNDR