Dave Herrell - Blog - IT Toolbox - PowerShell Banner

PowerShell Basics: Add Email Alias to all Users

You’ve just bought a new company, or maybe you just bought an awesome domain name.  Currently you are running a Hybrid setup so you will need to you will need to add this domain name as an alias to everyone in your company.  Time for a PowerShell script!

Adjust the script as needed below.  In this case were taking the users sAMAccountName for the beginning of the email address. Make sure you run as admin.  Be careful, you are about to add something to every user in your active directory!  Test this before running it! 

				
					# Define the new domain
$newDomain = "awesomenewdomain.com"

# Import Active Directory module
Import-Module ActiveDirectory

# Get all users in the Active Directory
$users = Get-ADUser -Filter * -Property sAMAccountName, ProxyAddresses

foreach ($user in $users) {
    # Construct the new smtp alias
    $newAlias = "smtp:" + $user.sAMAccountName + "@" + $newDomain

    # Check if the user already has a ProxyAddresses property, if not, create an empty array
    if (-not $user.ProxyAddresses) {
        $user.ProxyAddresses = @()
    }

    # Add the new alias to the user's proxy addresses
    $updatedProxyAddresses = $user.ProxyAddresses + $newAlias

    # Update the user's proxy addresses in Active Directory
    Set-ADUser -Identity $user -Replace @{ProxyAddresses = $updatedProxyAddresses}
}

Write-Output "SMTP aliases for $newDomain have been added to all user accounts."

				
			

Here is what the scripts doing:

  1. Defining the new domain for the smtp alias.
  2. Imports the Active Directory module. (make sure this is installed)
  3. Retrieves all user accounts and their sAMAccountName and ProxyAddresses properties.
  4. Constructs the new SMTP alias for each user.
  5. Adds the new alias to the user’s ProxyAddresses if it doesn’t already exist.
  6. Updates the user’s ProxyAddresses in Active Directory.

An important thing to note, we are Adding an alias on here, not changing the primary.  If you want add this new email domain address as your primary address, change the lowercase smpt to an uppercase SMTP.  The upper case SMTP is always the primary address where lowercase smpt in the ProxyAddresses attribute defines an alias address. 

 

Hope you find this helpful!