PowerShell - Replace Email with a new domain and add primary ProxyAddress

Dear Friends,

I’m new to PowerShell, and I’m working on a script to update the email attribute for users in Active Directory. I also want to add a primary SMTP address for multiple users using a CSV file in bulk thru a single script

My csv is in the below format;
sAMAccount, OldEmail, NewEmail, Primary Proxyaddress

Required Output is like this;
For each sAMAccount remove this email OldEmail and replace with this NewEmail and also add the new email as Primary (SMTP:) Proxyaddress

Can you provide what you have for your script so far?

Will it work ?

$csvPath = “C:\path\to\your\file.csv”

$users = Import-Csv -Path $csvPath

foreach ($user in $users) {

$sAMAccountName = $user.sAMAccountName
$newEmail = $user.NewEmail

$adUser = Get-ADUser -Filter {sAMAccountName -eq $sAMAccountName} -Properties EmailAddress, ProxyAddresses

if ($adUser) {

    Set-ADUser -Identity $adUser -EmailAddress $null

    Set-ADUser -Identity $adUser -EmailAddress $newEmail

    $proxyAddresses = $adUser.ProxyAddresses | Where-Object { $_ -notlike "SMTP:*" }
    $proxyAddresses += "SMTP:$newEmail"  # Primary SMTP is uppercase "SMTP:"

    Set-ADUser -Identity $adUser -Replace @{ProxyAddresses = $proxyAddresses}

    Write-Output "Updated email for $sAMAccountName to $newEmail and set as primary SMTP."
} else {
    Write-Output "User $sAMAccountName not found in Active Directory."
}

}

That looks like a good start. I’d suggest getting a test AD user, putting that user in the file, and walking through the script to see if it does everything you want.

Since you’re planning to run something in bulk against AD, I also recommend caution. It can be really easy when changing AD users in bulk to do something unintended, so limit the blast radius just in case. When you run it for real, maybe break your file into chunks, so that if something goes wrong, you’ve only impacted one portion of the users, not all of them.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.