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;
Import-Module ActiveDirectory Get-ADUser -Filter * -SearchBase 'DC=test,DC=net' | ` ForEach-Object { Set-ADUser -EmailAddress ($_.samaccountname + '@test.net') -Identity $_ }
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.
Import-Module ActiveDirectory Get-ADUser -Filter * -SearchBase 'DC=test,DC=net' | ` ForEach-Object { Set-ADUser -EmailAddress ($_.givenName + '.' + $_.surname + '@test.net') -Identity $_ }
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
18/01/2017
Excellent article. I’ve been searching the internet for a simple way to do this and Voila!! I found your article. Great Job
02/02/2018
I love you! It worked perfectly.
05/07/2018
Really good! Thanks
19/07/2018
Brilliant – thanks. Just had to stick in a couple of OU=subexample,OU=example to narrow it but worked perfectly.
20/12/2018
Super!
Very very Thank You!
16/01/2020
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
16/01/2020
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.
23/05/2020
how do you set the email address as blank for all users
29/05/2020
Set it to ‘null’ instead.
07/10/2020
Just Modify it to this:
ForEach-Object { Set-ADUser -EmailAddress ($_.givenName.ToLower() + ‘.’ + $_.surname.ToLower() + ‘@test.com’) -Identity $_ }
02/06/2021
Awesome, thank you so much for your contrinutions
05/08/2021
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 $_ }
24/08/2022
Very Nice