
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:
- Defining the new domain for the smtp alias.
- Imports the Active Directory module. (make sure this is installed)
- Retrieves all user accounts and their
sAMAccountName
andProxyAddresses
properties. - Constructs the new SMTP alias for each user.
- Adds the new alias to the user’s
ProxyAddresses
if it doesn’t already exist. - 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!
Categories
Recent Posts
- PowerShell: How to Add an Alias to Every Users Mailbox and Groups in Microsoft 365
- Slack: Disable Entra ID User using a slash command.
- Slack: Retrieve Entra ID (MS365) User Information with a slash command.
- Jira Cloud: Disabling Entra ID User Accounts via Automation and Microsoft Runbook
- Jira Cloud: Restart an Azure VM using JSM Assets and Automation