Let’s say you organization has migrated to a new domain name, and you need to update the email address field in AD. Manually edit a couple of hundreds of users are not ideal. Luckily we can use powershell to automate this work.

Step 1. Get an list of username and email address in CSV format:
Name email
AJ Abbey.James@frankfu.click
ALEA Aden.Alexander@frankfu.click
WATA Alex.Watson@frankfu.click
WARA Adrian.Waren@frankfu.click
AC Aik.Chow@frankfu.click

Note that the name here is the login name, which mapping SamAccountName in AD, email mapping email in the object property.

Step 2. Compose the powershell script
  1. Import the AD module first:
    Import-Module ActiveDirectory
  2. Import the data from CSV to a variable called $users
    $users=Import-CSV -path "C:\tmp\Email_update.csv"
  3. Loop through the $users, in each loop, we give the email property to the AD user property email
    • To verify the CSV file import is successful, we assign the properties to a temporary variable $username and $email , and echo them.
    • We use Get-ADUser to find the user with that login name (SamAccountName) in your domain (specified by SearchBase)
      Get-ADUser -Filter {SamAccountName -eq $username } -SearchBase "DC=frankfu,DC=click"
    • Then pipline it to Set-ADUser command, and  update the email field.
      Set-ADUser -Replace @{ mail=$email }
STEP 3 Putting all together

If we putting all of them together, and before run this script, I would like to add -whatIf in the Set-ADUser, just in case somewhere went wrong.

Import-Module ActiveDirectory

$users=Import-CSV -path "C:\tmp\Email_update.csv"

ForEach ($user in $users) 
{
$username=$user.Name
$email=$user.email

echo $username,$email

Get-ADUser -Filter {SamAccountName -eq $username } -SearchBase "DC=frankfu,DC=click"| Set-ADUser -Replace @{ mail=$email } -WhatIf

}

If you save this script and run it in Windows PowerShell ISE, it should show:

AJ
Abbey.James@frankfu.click
What if: Performing the operation "Set" on target "CN=AJ,OU=Teachers,OU=Staff,OU=Users,DC=frankfu,DC=click".
WARA
Adrian.Wareham@education.vic.gov.au
What if: Performing the operation "Set" on target "CN=ALEA,OU=Teachers,OU=Staff,OU=Users,DC=frankfu,DC=click".
AC
Aik.Chew@education.vic.gov.au
What if: Performing the operation "Set" on target "CN=WATA,OU=Support,OU=Staff,OU=Users,DC=frankfu,DC=click".

Bingo, now you can safely remove the -whatIf and let the script run!

 

Enjoy!