$oldUsername='testUser'
$newUsername='tUser'

function changeUsername{
param(
$oldUsername,
$newUsername
)
$domainName=$env:USERDNSDOMAIN
$newUserPrincipleName="$newUsername@$domainName"
try{
    Set-ADUser $oldUsername -SamAccountName $newUsername -EA Stop
    write-host "$oldUsername has been changed to $newUsername"
    Set-ADUser $newUsername -UserPrincipalName $newUserPrincipleName -EA Stop
    write-host "$newUsername UserPrincipleName has been updated to $newUserPrincipleName"
}catch{
    write-warning $_
}
}

changeUsername $oldUserName $newUsername