PowerShell – Updating Users Email Addresses In Active Directory

KB ID 0001216 

Problem

Note: I’m referring to the Email address value that is listed on the user object in Active Directory, this will not effect any Exchange Settings!

A colleague asked me today if I had any PowerShell to update ALL the users in a clients AD, to match their UPN to their Email addresses. A quick internet search turned up loads of handy scripts to update the UPN to mach the email address, but not the way round he wanted.

Solution

In most (not all) cases your UPN is the same as your sAMaccountname and your domain name, so you can simply run the following;

[box]

Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'DC=test,DC=net' | `
    ForEach-Object { Set-ADUser -EmailAddress ($_.samaccountname + '@test.net') -Identity $_ }

[/box]

Note: Save the above as a file with a .ps1 extension, or execute both commands separately.

Now you may, (like on my test network above,) have your user logon name set to something other than firstname.lastname if so and you would prefer to set the Email value to firstname.lastname@domain.com then use the following instead.

[box]

Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'DC=test,DC=net' | `
    ForEach-Object { Set-ADUser -EmailAddress ($_.givenName + '.' + $_.surname + '@test.net') -Identity $_ }

[/box]

Note: Save the above as a file with a ps1 extension, or execute both commands separately.

Related Articles, References, Credits, or External Links

PowerShell – Update All Domain Users With Email Address From UPN

13 thoughts on “PowerShell – Updating Users Email Addresses In Active Directory

  1. Excellent article. I’ve been searching the internet for a simple way to do this and Voila!! I found your article. Great Job

  2. Brilliant – thanks. Just had to stick in a couple of OU=subexample,OU=example to narrow it but worked perfectly.

  3. The script worked great, just 2 questions, how do you make the email address all lowercase and also remove extra characters in the surname

    i.e O’Brien would become obrien

    • Email addresses are not case sensitive? For extra characters I’d run a Get-ADuser and parse for usernames, display names or samaccount names that contain them and manually do them.

    • Just Modify it to this:

      ForEach-Object { Set-ADUser -EmailAddress ($_.givenName.ToLower() + ‘.’ + $_.surname.ToLower() + ‘@test.com’) -Identity $_ }

    • I modified this further so it would fill the email address using the UserPrincipalName information.

      It would also only search the default new user location.

      $domain = get-addomain
      $OU = $domain.UsersContainer

      Get-ADUser -Filter * -SearchBase $ou | `
      ForEach-Object { Set-ADUser -EmailAddress $_.UserPrincipalName -Identity $_ }

Leave a Reply

Your email address will not be published. Required fields are marked *