79636037

Date: 2025-05-23 18:33:36
Score: 2
Natty:
Report link

Thank you @mathias

I found this article while looking for a way to script changes for an email domain name change on local AD that was synced to 365. I wanted to be able to have a precise lookup and be able to use variables to fill the right alias into the account in preparation for the migration to the new domain. While this got me closer than anything else I found online (which I found so hard to believe), I was challenged with getting to operate properly on a server that had way too many differences between SamAccountName and GivenName. I also wanted to have something that was less specific and provided options for future use across multiple clients we support that are Azure ADSynced. Enjoy.

$proxydomain = "@domain.com"
$OUpath = 'OU=Users,OU=FOLDER,DC=domain,DC=local'
     Get-ADUser -Filter {(Enabled -eq $true -and UserPrincipalName -notlike '*.local')} -SearchBase $OUpath -SearchScope Subtree -Properties *  | foreach-object {
    
    # Create user alias from user account information. 
    # Various options provided, adjust comment header to select the format you wish
    # NOTE THAT "smtp" ON THESE ARE LOWER CASE, MAKING THEM ALIASES, NOT PRIMARY EMAIL ADDRESSES
    $alias = ("smtp:{0}{1}$proxydomain" -f $user.GivenName.Trim()[0], ($user.Surname)) #[email protected]
    #$alias = ("smtp:{0}{1}{2}$proxydomain" -f ($user.GivenName), ".", ($user.Surname)) #[email protected] WATCH FOR MIDDLE INITIALS!  You may need to replace GivenName with SamAccountName or use other trim methods.
    #$alias = ("smtp:{0}$proxydomain" -f ($user.GivenName)) #[email protected]

   # -match is a regex operator, escape appropriately
    if ($_.ProxyAddresses -match [regex]::Escape($alias)) {
        Write-Host "Result: $alias value already exists for user $($_.displayname); No action taken."
    }
    else {
        # Now we only have a single variable that needs to be expanded in the string
        Set-ADUser -Identity $_.SamAccountName -Add @{proxyAddresses = "$alias"}
        Write-Host "Result: Added $alias value to $($_.displayname)"
    }
}
Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Blacklisted phrase (1): this article
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @mathias
  • Low reputation (1):
Posted by: ComputerSuperheroes