Rename AD users with Powershell

We need to change the name of our users in Active Directory. Not just the displayname, but also the distinguishedname. The following script will show you how to do that:

#Rebrand-Users.ps1

#Variables - edit as required
################################################################
$Sitecode = "HQ"
$container = "OU=ImportedUsers,DC=GREGDOM,DC=INT"
$server = "gregdom.int"
$company = "MyCompany"
################################################################

#Read users into variable.
$users = get-aduser -filter * -SearchBase $container
 
#Process users.
Foreach ($user in $users) {
    $newDN = $user.surname + ", " + $user.GivenName + " ($sitecode)"
	#Change display name, and company name
	set-aduser $user -Displayname $newDN -company $company -server $server -ErrorAction SilentlyContinue
	#Change distinguished name
		Try {
    		Rename-ADObject -identity $user -Newname $newDN -server $server 
		}
		Catch {
			Write-Host "$user may already exist."
		}
    }

Note that it is basically a two step process, once to change the display name, and then again to change the distinguished name, which cannot be done with set-aduser.

Advertisements

Leave a comment

Filed under Microsoft, Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s