Powershell Script to Change Username in Active Directory, Exchange Alias, and Office 365 UPN

When a user changes their last name with our organization, I have to rename the user in several places Active Directory, Exchange mailbox alias, and Office 365 UserPrincipalName. There are several issues that can cause a problem.  If the new username is not available, whether the user’s mailbox has been migrated to Office 365, and the time involved in making all of these changes.  I wanted a quicker and easier way to change a user’s name, username, and exchange alias.  In our setup we are using Azure AD Connect with AD synchronization to Office 365 and Exchange hybrid mode.

There can be other issues with changing a username:

  • OneDrive Business Synchronization will break on the user’s desktop or laptop.
  • Local Office Login (Word or Excel) to Office 365 will break on the user’s desktop or laptop.
  • My Documents Path might need to be changed (this change could be scripted if the directory is not in use or mapped)
  • Contact information will need to be changed on the phone system, voicemail, etc.

However, a script to help with the process of changing a username saves time and effort.  You can add more error checking if needed.  Not everyone’s setup in their organization is the same, but this could give you the sample code needed to change what is necessary in your organization.  This script is not automated.  You add in the needed information at the top, run the script, and enter the credentials needed.

Prerequisites:

 

 

#Rename a User Account because of a Last Name Change or First Name Change, changes username in AD, Exchange Alias, and Azure AD UserPrincipalName
#This script is for an organization that synchronizes Active Directory with Office 365 and the user's first or last name and username needs to be changed
#This script must be run from the server with Azure AD Connect installed
#This script must be run from a powershell script with Administrator privileges for the ADSync commands to work.
#Review the script below and change the information as needed
#Added checking for prexisting email aliases 1-18-2018

#Install-Module -Name AzureAD 
#Update-Module -Name AzureAD 
Import-Module AzureAD
Import-Module ActiveDirectory;
Import-Module ADSync;

#Edit Variables Here:
#Old Name
$oldfirstname='';
$oldlastname='';
$oldusername='';        #old username

#New Name
$newfirstname='';
$newlastname='';
$newusername='';        #new username 
$aliasExists = $True

$logfile = 'c:\temp\UserRenamed.txt';

#DisplayName and AD Object Name Format:
$newdisplayname = "$newlastname, $newfirstname";

#UPN Format:
$oldupn="$oldusername@Office365EmailDomain.com";
$newupn="$newusername@Office365EmailDomain.com";

#Leave Variables alone below unless fixing a problem or if you have a different setup:

#Office 365 Credential Request
WRITE-HOST "Office 365 Credential Request";
$msolcred = get-credential;

#Local Exchange Admin Credential Request
WRITE-HOST  "Exchange Admin Credential Request";
$cred = get-credential;

WRITE-HOST "oldupn:$oldupn";
WRITE-HOST "newupn:$newupn";

$errormessage = "Start User Rename oldusername:$oldusername to newusername:$newusername";
Add-Content $logfile $errormessage;

#check if newusername already exists (could be a problem)
try 
{
    $user = Get-ADUser -Filter "sAMAccountName -eq '$newusername'" -SearchBase 'DC=CONTOSO,DC=com' -Properties cn,displayname,givenname,initials;
}
catch
{
    $errormessage ="Error New Username Already Exists";
	WRITE-HOST $errormessage
}




#new username does not exit then we can move forward
if ($user -eq $null) 
{

    #Check if the new alias already exists
    #I have not tested this new section yet.
    #Exchange Connection/Session
    $sessionoption = New-PSSessionOption -SkipCNCheck;
             
    #Local Exchange Session
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://LocalExchangeServer/powershell/ -Credential $cred -AllowRedirection -SessionOption $sessionoption;

    Import-PSSession $Session;

    $aliasExists = $True
    try 
    {
        #Checking if email address alias already exists in Exchange
        $localAliases = Get-Mailbox -ResultSize unlimited | where { $_.emailaddresses -like "smtp:$newusername*" } 
        $remoteAliases = Get-RemoteMailbox -ResultSize unlimited | where { $_.emailaddresses -like "smtp:$newusername*" }
        if ($localAliases -eq $null -and $remoteAliases -eq $null)   
        {
            $aliasExists = $False
            WRITE-HOST "New Email Address Alias is Unique for $newusername."
        }
        else
        {
            $errormessage = "Error: New Email Address Alias is Not Unique for $newusername!";
            Add-Content $logfile "$errormessage $_";
            WRITE-HOST $errormessage
        }
    }
    catch
    {
        $errormessage = "Error checking the email address alias existence for $newusername";
        Add-Content $logfile "$errormessage $_";
        WRITE-HOST "Exchange Alias check if already exists failed!";
    }
    #Exit Session
    Remove-PSSession $Session;


    if ($aliasExists -eq $False)
    {
        try 
        {
            #Get the old user object and verify it exists and will use the DN later
            $user = Get-ADUser -Filter "sAMAccountName -eq '$oldusername'" -SearchBase 'DC=CONTOSO,DC=com' -Properties cn,displayname,givenname,initials;
    
        }
        catch
        {
            $errormessage = "Error occurred looking up User with sAMAccountName '$oldusername' does not exist in the target OU.";
            Add-Content $logfile $errormessage;
        }

        if ($user -eq $null) 
        {
            $errormessage = "User with sAMAccountName '$oldusername' does not exist in the target OU.";
            Add-Content $logfile $errormessage;
        }
        else
        {
            # Try to modify the user account's username and upn, trapping errors if they occur
            try 
            { 
                $userDN=$($user.DistinguishedName);
                WRITE-HOST "Rename DN:$userDN";
                Set-ADUser -identity $userDN -sAMAccountName $newusername -UserPrincipalName $newupn -DisplayName "$newlastname, $newfirstname" -SurName $newlastname -GivenName $newfirstname -ErrorVariable Err;
                Start-Sleep -Seconds 30;
                rename-adobject -identity $userDN  -newname "$newlastname, $newfirstname";
                Add-Content $logfile "User renamed in AD";
                WRITE-HOST "User Renamed Successfully";
            }     
            catch 
            {
                $errormessage = "Error renaming the user account $oldusername";
                Add-Content $logfile "$errormessage $_";
                WRITE-HOST "User Rename Failed!";
            }

            Start-Sleep -Seconds 60;

            #Exchange Connection/Session
            $sessionoption = New-PSSessionOption -SkipCNCheck;
        
            
            #Local Exchange Session
            $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://LocalExchangeServer/powershell/ -Credential $cred -AllowRedirection -SessionOption $sessionoption;

            Import-PSSession $Session;

            #Fix Alias with Exchange
            try 
            {
                #Fixes the Alias with Exchange to be the $newusername
			    $exist = [bool](Get-Mailbox -identity $oldusername -ErrorAction SilentlyContinue);
			    if ($exist)
			    {
				    #Mailbox is on local exchange server
				    Get-Mailbox -Identity $oldusername | Set-Mailbox -Alias $newusername
			    }
			    else
			    {
				    #Mailbox has been migrated to Office 365 Exchange Online
				    Get-RemoteMailbox -identity $oldusername | Set-RemoteMailbox -Alias $newusername;
			    }
                WRITE-HOST "Exchange Alias Changed Successfully newalias:$newusername";
            }
            catch
            {
                $errormessage = "Error changing the alias for $newusername";
                Add-Content $logfile "$errormessage $_";
                WRITE-HOST "Exchange Alias change failed!";
            }
            #Exit Session
            Remove-PSSession $Session;

            Start-Sleep -Seconds 120;
            #Synchronize local AD and Azure AD
            Start-ADSyncSyncCycle -PolicyType Delta;
            Start-Sleep -Seconds 180;

            #Connect to Azure AD Online
            Connect-AzureAD -credential $msolcred;

        
            try 
            {
                #Fix UserPrincipalName with AD Online
                Set-AzureADUser -ObjectId $oldupn -UserPrincipalName $newupn;
                WRITE-HOST "Azure AD userprincipalname updated to $newupn"
            }
            catch
            {
                $errormessage = "Error renaming the upn with AD Online with the oldupn:$oldupn newupn:$newupn";
                Add-Content $logfile "$errormessage $_";
                WRITE-HOST "Azure AD userprincipalname change failed!";
            }
            Disconnect-AzureAD
        
        }
    }
}
else
{
    $errormessage = "New Username with sAMAccountName '$newusername' already exists!";
    Write-Error $errormessage;
    Add-Content $logfile $errormessage;
    
}
$errormessage = "Finish User Rename oldusername:$oldusername to newusername:$newusername";
Add-Content $logfile $errormessage;
WRITE-HOST "Username Change Script Completed Running.";
WRITE-HOST "If OneDrive synchronization is used by the user then reimaging their computer might be necessary";

Resources:

https://technet.microsoft.com/en-us/library/bb123685(v=exchg.160).aspx

https://docs.microsoft.com/en-us/powershell/msonline/v1/set-msoluserprincipalname

https://technet.microsoft.com/en-us/library/hh852287(v=wps.630).aspx

https://msdn.microsoft.com/en-us/library/ms680857(v=vs.85).aspx

https://technet.microsoft.com/en-us/library/jj614536.aspx

Leave a Reply

%d bloggers like this: