Rename displayName and CN from givenName and surName with Powershell?
I need to reconcile the displayName
and CN
attributes to the givenName
and surName
fields in AD.
Is it possible to take givenName
and surName
and rename both the displayName
and CN
using Powershell?
Powershell really shines for clean-up tasks like this.
Import-Module ActiveDirectory
$allUsers = Get-ADUser -Filter * -Properties cn,displayName
foreach ( $u in $allUsers | Where-Object { ($_.givenName) -and ($_.surName) } ) {
$fn = $u.givenName.Trim()
$ln = $u.surName.Trim()
Write-Host $fn $ln
Set-ADUser -Identity $u -DisplayName "$fn $ln" -GivenName "$fn" -SurName "$ln" -PassThru |
Rename-ADObject -NewName "$fn $ln"
}
Caveats:
- I'm
Trim()
ing thegivenName
andsurName
to remove leading/trailing spaces. We commit these two back to the account, as well as correctingdisplayName
andcn
. - Scope your
-Filter
inGet-ADUser
to only gather the users you want. The*
will grab everyone in the domain, including built-ins, admins, etc. This probably isn't what you want. :) - The
Where-Object
portion of theforeach
will skip user objects that do not have both agivenName
andsurName
attribute. - If you need to play with the renamed user object, add a
-PassThru
to the end of theRename-ADObject
line and the object will be passed back to you.