Renaming AD User Object Surname Property.

The following script renames the Surname property of an Active Directory User Object. The script requires PowerShell 3.0. The only edit required is the organizational Exchange Server name specified in the New-PSSession cmdlet.

The script accepts the Given Name, Surname and new Surname parameters’ input from the console,executes the rename of the Active Directory object and inserts the new Exchange email attribute. It then sets the new email address as the Primary smtp email and removes the current exchange session.

function Rename-ADUser {

$firstName = (Read-Host "Enter Current FirstName"),
$lastName = (Read-Host "Enter Current LastName"),
#$newfirstname = (Read-Host "Enter New FirstName(If unchanged, Press Enter)"),
$adforest = (Get-ADForest),
$newlastname = (Read-Host "Enter New LastName"),
$userPrincipalName ="$firstname" + "$lastname" + "@" + ($adforest.Name),
$name = "$firstName" +" " + "$lastName",
$sam = "$firstname" + "$lastname",
$alias = "$firstname" + "$lastname",
$newname = "$firstName" +" " + "$newlastName",
$newsam = "$firstname" + "$newlastname",
$newalias = "$firstname" + "$newlastname",
$newuserPrincipalName ="$firstname" + "$newlastname" + "@" + ($adforest.Name),
$newemailaddress ="$firstname" + "." + "$newlastname" + "@" + ($adforest.Name)


#if ($newfirstname -eq "") {$newfirstname = $firstName} ;
#if ($newfirstname -eq $NULL) {$newfirstname = $firstName}
#if ($newlastname -eq "") {$newlastname = $lastName};
#if ($newlastname -eq $NULL) {$newlastname = $lastName}
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeserver/powershell
Import-PSSession -Session $s -AllowClobber
Get-ADUser -Identity $sam | Rename-ADObject -NewName "$newname"
Get-ADUser -Identity $sam |Set-ADUser -Surname $newlastname -DisplayName $newname -SamAccountName $newsam -UserPrincipalName $newuserPrincipalName -EmailAddress ("$firstname" + "." + "$newlastname" + "@" + ($adforest.Name))
Set-Mailbox -Identity $alias -EmailAddressPolicyEnabled $false
Set-Mailbox -Identity $alias -PrimarySmtpAddress ("$firstname" + "." + "$newlastname" + "@" + ($adforest.Name)) -Alias ("$firstname" + "$newlastname")
Remove-PSSession -Session $s

I’m open to any improvements and updates to the script. I hope this is helpful.

This entry was posted in Active Directory, Exchange 2010 SP2, Exchange Cmdlets, Exchange Management Shell, PowerShell, PowerShell 3.0, WIndows 8.1, Windows Server 2012, Windows Server 2012 R2 and tagged , . Bookmark the permalink.

Leave a Reply

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

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

Facebook photo

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

Connecting to %s