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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#############################################################################################
# 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:

1
.\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!

Licensed under CC BY-NC-SA 4.0
Zuletzt aktualisiert am Feb 15, 2012 22:48 UTC
comments powered by Disqus
Developer / Inventor / Creator
Erstellt mit Hugo
Theme Stack gestaltet von Jimmy