Powershell – Rename domain computer remotely (within an active directory domain as well)

I wanted to rename a couple of computers within our active directory. After some research i figured out thats it seems to be nearly impossible to rename a computer by just touching one object: the ad computer object, or the computer (client) itself. My first thought was “ok, you have to rename both objects, rejoin the computer and hope everything works”. But that’s no solution, that makes me happy, because the more steps you do, the more problems can occure. For examples, what happens if the computer has to reboot, after renaming to get correct rejoined? Do i have to create a local admin account at the clientside to have permissions after the computer lost his connection to ad? And so on…
I played around, renamed the ad object, rebooted it – negative, the computer has to be joined again. After that i tried it the “bottom up” way by renaming the computer by hand, and rebooted it instantly. While the computer was shutting down i noticed, that the computerobject in active directory was renamed before the computer was finished with its shutdown process.
So i tried this several times and every time the ad computerobject was renamed properly. YAY!
I had my solution. It can’t get more easy to rename a computer without rejoining it.

After this conclusion i tried to do it remotly with powershell, so i googled and found some sites about using netdom.exe. But, yep, right, calling a remote program was not the way i want to solve this problem :). I found some information on using wmi that suits me, so i started writing a powershell script to test it. As expected it’s a bit complicated to rename a computer within a domain by wmi. You have to overcome 3 “hurdles”:
- Use Authentication
- Using username and passwort of an administrative account
- Reboot the computer instantly after renaming

Here is a script, that does everything you want. Rename the computer and reboot it if renaming was successfull. Look at the variable section at the script header and fill in your administrative credentials (~domain admin)

#############################################################################################
# Parameterlist
#############################################################################################
param([string] $computername,[string] $newcomputername)

#############################################################################################
# Module import
#############################################################################################
# For checking if the computer exists in AD
import-module activedirectory

#############################################################################################
# Variable
#############################################################################################
$ADUserName = "ad\myuser"       # Don't forget to add your domain
$ADUserPassword = "MySecretPW"

#############################################################################################
# POWERSHELL Ping tool to check if a computer/ip/hostname is online
#############################################################################################
function isComputerOnline( $comp ){
    trap [Exception] {
        return $false
   }
    if ( $(new-object system.net.networkinformation.ping).send( $comp ).status -eq "Success" )
    {
        return $true
    }else{
        return $false
    }
}
 
#############################################################################################
# Remote Rename Computer by WMI
#############################################################################################
function COMPUTER_RENAME([string] $oldComputerName, [string] $newComputerName){
	# should implement further checks for the computername. If computername uses illegal characters and if computername is longer than 15 characters
	# More information here: http://labmice.techtarget.com/articles/computernaming.htm
    $oldComputerName = $oldComputerName.replace(" ","");
    $newComputerName = $newComputerName.replace(" ","");
    # // Check if the computer is online
    if ( isComputerOnline $oldComputerName ){
		# // Check the active directory if a computer with your provided newcomputername already exists.
		# // If you want to use the script without active directory just comment (use: #) this line and the corresponding "else" loop
        if ( ! (Get-ADObject -ldapfilter  "(CN=$newComputerName)") ){
            # // Handle every upcoming error as a stop failure, so you can trap it
            $ErrorActionPreference = "Stop"
            try{
                # // Get the WMI Object of the remote computer
                $ComputerWMIObject = Get-WmiObject Win32_ComputerSystem -ComputerName "$oldComputerName" -Authentication 6
                if ( $ComputerWMIObject ){
                    # // Rename the Computer Object with your or some admin credentials (Yes, Passwort is the second parameter and username the third )
                    $result = $ComputerWMIObject.Rename("$newComputerName", $ADUserPassword , $ADUserName )
                    # // Switch Case for the returnvalue of computer renaming function
                    switch($result.ReturnValue)
                    {
                        0 {
                            # // Reboot the computer instantly if renaming was successfull
                            Get-WmiObject Win32_OperatingSystem -ComputerName "$oldComputerName" |
                            ForEach-Object {$restart = $_.Win32Shutdown(6)}
                            write-host "Computer $oldComputerName was renamed ($newComputerName) and restarted"
 
                        }
                        5 { write-host "Computer was not renamed. Please check if you have admin permissions (ReturnCode 5)"; exit; }
                        default { write-host "ReturnCode $($result.ReturnValue)"; exit;}
                    }
                }else{
                    write-host "Couldn't create WMI Object on $oldComputerName"
                }
            }catch{
                write-host $_
            }
        }else{
            write-host "There is already a computerobject with the name $($newComputerName)"
        }
    }else{
        write-host "Computer is offline!"
    }
}

if ( $computername -and $newcomputername ){
	COMPUTER_RENAME $computername $newcomputername
}else{
	write-host ""
	write-host "Script Usage: RenameComputer.ps1 -computername ""Current-Computer-Name"" -newcomputername ""New-Computer-Name"""
	write-host ""
}

Due to some issues with copy and paste of this sourcecode, there is a download (zip) available here -> Rename Computer Powershell Script.
After you have downloaded and extracted the zip file, edit the script with your favorite editor (I always use notepad++ or notepad). At the beginning of the script, there is a section called variable. You have to enter your Active Directory username (with ad forrest) and the corresponding password.
Now start your Powershell and go to the directory where your script is and start it with the following command:

.\RenameComputer.ps1 -computername "CurrentCompName" -newcomputername "NewCompName"

There is no check on the computername yet, so every computername you submit is more or less valid.
More information about the limitations of a computername can be found here: http://support.microsoft.com/kb/909264/en-us

Feel free to use this script and leave me a comment!

52 thoughts on “Powershell – Rename domain computer remotely (within an active directory domain as well)

  1. You can actually download the script @ this address : http://dl.free.fr/hLG3mzgkY

    You just have to input Domain + Account + Password (Delegation or admin rights for this account have to exist on your AD/needed OUs to alter computer objects’ name) in the script.
    [And perhaps changing the name of the TS variable ("$TSEnv:NewOSDComputerName") in order to match yours...]

    In the TS, please respect these steps:
    -1 : Install WMF 3.0 update on the freshly deployed and running OS + Restart Computer,
    -2 : Set PSExecutionPolicy to a lower level,
    -3 : Run the Script + Restart Computer,
    -4 : Set PSExecutionPolicy back to Default.

    That’s all ! =)

    Best regards,
    Seb.

  2. Hi, Marco

    i try to use your script to rename my domain computer, it succeed and very helpful to me, and now, i need to bulk rename my domain computers, is anyway to rename computers with csv files ?

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>