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 {
param(
$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
}
Rename-ADUser
I’m open to any improvements and updates to the script. I hope this is helpful.