Zum Inhalt springen

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)

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:

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!

Published inCodingPowershellScriptingWMI

55 Kommentare

  1. Eli RIpoll Eli RIpoll

    Hi great work. I am new to powershell and i was hoping you could help me use the script you provided. After i save the script do i save the script as a ‘ .ps1’ ?
    after i save the script what is the proper syntax to run the script against a computer?
    i tried .\pcrename.ps1 ‘old computername’ ‘newcomputername’

    any help would be great thanks again

    • I provide you a working script tomorrow, when im on a computer and not on my iphone :)

  2. Hey Eli,
    I edited the posting, now you can copy the sourcecode and use the script as described in my posting.
    Hope that helps you get this script running :)

  3. Cam Cam

    This requires the AD server to be Server 2008 R2?

    • I don’t know if this is only works with windows server 2008 R2. I don’t have any other active directory running at the moment. I thougth that this would work with 2003 as well, because this way of renaming a computer is the only way to ensure that the client and server notice the renaming at the same time. Have you tried it with an other server os version?

  4. Cam Cam

    After a little searching I’ve determined that the ADWS can be installed on windows server 2003 or later. The service itself runs as the 2008 R2 service. Thanks for the quick reply.

    • Thanks for your comment. I didn’t knew, that ADWS isn’t part of windows 2003 server. It’s a long time since we were on w2k3.

  5. Cam Cam

    Excellent script. It works exactly as advertised. I know it’s a long-shot, but I have a request. Would it be possible for me to write a script that I could put into my windows directory. Where I could type at the command prompt “pcrename compname1 compname 2” and have it take those two variables and enter them into your script? My thanks either way.

  6. Cam Cam

    Thinking about it, it doesn’t need to be a batch file ran out of command prompt. I guess I just want to get it down to “.\pcrename.ps1 $input1 $input2”. Where those represent -computername and -newcomputername

    Thanks again

  7. Cam Cam

    I got it, thanks.

    Set-Alias pcrename “c:\scripts\pcrename.ps1”

    function gdi($1,$2)
    pcrename $1 $2

  8. Hey Cam,
    thank you for your comment. Maybe someone else will use the script like you do.
    I read your comment yesterday on my mobile and your solution was the first one i had in mind, but I couldn’t test it at that moment.
    Great that it had worked out.

  9. Ed Ed


    I get ReturnCode 87 and nothing seems to change, what haven’t I done that I should have done?


    • Hi Ed,

      we use this script daily.
      Returncode 87 could be something like: “one of the parameters was invalid. -> ERROR_INVALID_PARAMETER”
      What system are you connecting to? Which service pack?
      Maybe there is an problem, because the parameters have changed or something like that.

  10. Michael Michael

    Hi there… Maybe I am just too stupid… But how exactly do I copy this script out of the webpage? I have tried selecting the text and pasting into notepad but the text gets all jumbled up… Could somebody please educate me? lol Thank you.

  11. Hi Michael,

    try a double click at the source code. Maybe the line feeds wrapped everything up. :)
    In addition, i sent the script within a text file to your email address. Hope that works for you.

    Kind regards

  12. Michael Michael

    Hi Marco. Thank you. Double clicking the text selects it much easier however pasing it into notepad still looks funny… Does it matter if the pasted text does not look like the structure you have on the webpage? Also, if it’s not too much trouble… could you email me that code at the email address I have provided (it is a different one now) I think my corporate spam server stopped your first email. Thank you again!

    • Hey Michael,
      alright, the script is on its way :).
      I think you get problems if the script is not formatted correctly, because i didn’t finish every line with an ending semicolon.
      Please let me know if the emailed script has correct line breaks.
      Marco :)

  13. Michael Michael

    Hi Marco. Thanks the email came through. I am getting this error when I run the script:

    The term ‘Get-ADObject’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check th
    e spelling of the name, or if a path was included, verify that the path is correct and try again.
    At C:\Users\mlcard\Desktop\renamecomputer.ps1:33 char:29
    + if ( ! (Get-ADObject <<<< -ldapfilter "(CN=$newComputerName)") ){
    + CategoryInfo : ObjectNotFound: (Get-ADObject:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Sorry I am VERY new to Powershell and basically know nothing yet. Do you think you could help me with this error? Thanks again.

  14. Michael Michael

    Hi Marco.

    First off.. Thank you so much for helping me. It’s very nice when somebody takes time out of their busy day to help a stranger. I now can run the script but it gives me a “ReturnCode 2202” message. Is this an error? The computer name did not change… Thank you so much again!

  15. Michael Michael

    Oh!!! I got it! I did not enter my domain credentials in the script… I am so happy right now. lol

    Marco, you are the best!

  16. Hey, i was writing a comment right now, to let you know that all error messages are normal windows error messages. So you can easily google them. (error 2202 = username invalid)
    But you were faster. 😀
    I’m happy that my script works at your site!!

    Have fun with it!

  17. Christian Christian

    Hi Marco,

    Firstly thanks for the script, had a few problems my self with copying script, I realised it was IE being, well IE, chrome I didnt have a problem pasting it into Notepad++

    Secondly I couldn’t get it to work in Windows 7, so went on a 2008 R2 box instead.

    Thirdly, I had the issue the same as Michael, again, the comments fixed it for me :)

    Finally Its worth mentioning that people need to change some more lines:
    Line 41 holds credentials to be changed, not 32 as you advise
    Line 73 needs the .ps1 changing to the name of the script, eg myrenamescript.ps1
    Line 75 needs removing otherwise the error ‘The term ‘<' is not recognized as the name of the cmdlet' appears – Simple stuff I know, but may help the newbies, like me, that had to work that out!

  18. Hey Christian,

    thank you for your comment. It should run on Windows 7 (i thought i have tested it at my W7 box)… I will try this today and correct my post if it doesn’t work. Based on your comment I edited my posting and added a download for my script to prevent these weird copy and paste issues. I also added two variables for the username and password to the header of my script. This is much clearer, than changing the username/password somewhere in the script. I hope this helps these users who are not so familiar with powershell.

    I’m happy that it worked for you in the end :). Exuse my little tripping hazards!

    Kind regards

  19. Klaus Klaus

    Hi Marco,

    I open Powershell with systemmodules importing (right mouse) on a 2008-R2 Domain Controller and start there your PS-scipt with both parameters.
    After a few seconds i get following message (translated from german):
    “The RPC-Server is not available. (Exception of HRESIULT: 0x800706BA).”

    By the way, i would prefer to type the admin-password as parameter and not to store it in a file.

    Kind regards and thanks for help

    • Hallo Klaus,

      danke für dein Kommentar.
      Dass der RPC-Server nicht verfügbar ist weisst schon darauf hin, dass etwas mit der Verbindung nicht stimmt.
      Vielleicht liegt es einfach an der Firewall. Um einen relativ einfachen Test zu fahren kannst du in der Powershell mit “get-wmiobject -computername ” schon mal versuchen, ob du auf den Zielrechner kommst (ohne den ganzen Authentifizierungs overhead). Noch einfacher geht es mit Telnet, um zu sehen, ob der Port überhaupt offen/erreichbar ist “Telnet 135″

      Sollte das nicht gehen kannst du mal auf dem entfernten Client gucken, ob dort die Firewall Einstellungen korrekt sind. Falls möglich einfach mal kurz abschalten um zu sehen, ob der WMI Befehl funktioniert, oder nicht. Wenn es an der Firewall liegt kann man diese dann entsprechend so konfigurieren, dass sie die Verbindung für RPC Calls zulässt und zwar mit “netsh firewall set service remoteadmin enable”.

      Falls das nichts bringt, dann bitte auch mal die Dienste durchgehen. Es ist zwar relativ unwahrscheinlich, aber es kann auch manchmal sein, dass der Remoteprozeduraufruf (RPC) Dienst nicht läuft (man hat ja bekanntlich schon Pferde kotzen sehen).

      Vielleicht gibt es auch hinweise im Eventlog, aber das kann eine lange Suche werden.

      Ich hoffe das hilft, andernfalls schreib einfach noch einmal :)

      Viele Grüße und viel Erfolg

      p.s. was ist denn das Client Betriebssystem?

      Short english version
      Check if your firewall doesn’t block the incoming (and outgoing) RPC Calls. The fastest way to test if there is an firewall issue is to turn it off (nearly impossible at serverside). To do a quick check if RPC Calls would work try a short command from powershell: “get-wmiobject -computername “. More easier to check if port 135 is listening: “Telnet 135″.

      If it’s a firewall issue try to grant the remoteadmin services access with the command: “netsh firewall set service remoteadmin enable”.

      If you are sure, that your firewallsettings are fine and the rpc calls still doesn’t work, check if your remoteprocedurecall (RPC) service is running at your target box.

      That should do the trick (hopefully).
      Otherwise you should check your eventlog to see if there is something happening in the background.

  20. Daniel Daniel

    Thank you for the script. It works like charm after changing two settings:
    Set-ExecutionPolicy RemoteSigned
    import-module ActiveDirectory

    Next step is to make it possible to massexecute name-changes with a batch-file containing:
    .\RenameComputer.ps1 -computername “CurrentCompName1” -newcomputername “NewCompName1”
    .\RenameComputer.ps1 -computername “CurrentCompName2” -newcomputername “NewCompName2”
    .\RenameComputer.ps1 -computername “CurrentCompName3” -newcomputername “NewCompName3”
    What is the best practice for this? Can I call on PS1-scripts from a bat-file or something?

    • Hi Daniel,

      thank you for your comment. The AD module import is missing, thats correct. I add it when i’m back home.
      The executionpolicy has only to be set once per machine. Not every time you call a script.

      To answer your question. Yes, it’s possible to call ps1 files from batch files, but you have to add powershell.exe and some parameters in fromt of your calls.
      The easiest way is to put your calls into a (let’s call it) batchrename.ps1 and execute it via powershell .\batchrename.ps1

      That should do the trick 😉

      Kind regards

  21. Daniel Daniel

    Ok, thank you for the reply. You do not need to import the modules manually if you start the “Active Directory Module for Windows PowerShell” under Administrative Tools on a Windows 2008R2 Domain Controller or a Computer with RSAT installed. I tried runnig the command in a batch like you suggested, .\Batchrename.p1 worked just fine. I had just one computer to try on, but the script worked.

    • We use this script in an automation process, called by a webservice. The module import is helpfull for this scenario :).
      But i agree with you, it is not really necessary.

  22. Daniel Daniel

    “We use this script in an automation process, called by a webservice”. Sounds interesting. Tell me more!! :-)
    Where do you put the “import-module ActiveDirectory” string in the script?

    • :D. Just a small insight.
      We manage nearly 10k clients in one AD site via a self developed (by me) administrator portal (webbased + Webservice based + powershell) with some process automation, like those powershell scripts in the background. Everything in the back is wrapped by a webservice, that fires some powershell scripts to activate users, or create shares, set quota, add computers (for deployment via SCCM) and so on. If the action isn’t too complex the webservice does its work directly with our AD, like adding users, or computers to groups.
      We had to go this way, because we don’t want to give every admin (over 50) the ability to work with the normal AD administration tools. Even because you need 3 tools to add a share, add a dfs link and set the quota (without setting AC). With our web admin portal its more or less one click away :).
      In the meantime, we use this admin portal 98% of our time for managing our environment and fall back to the normal AD tools only in case of emergency.

      That’s the reason, among other things why I put the import module in the first line (to answer your question) of a script. It’s easier to start a normal powershell.exe process from a webservice, than one with AD modules :).

      p.s. I added the import module to the script

  23. Marshall Marshall

    Hey Marco,

    Thanks for this. It will come in handy renaming a lot of computers to include their asset tags since we have recently gone around and tagged them. I want to do this during business hours while people are working, but I dont want to shut them down suddenly and I dont want to have to go around and explain it to everyone, would like it to be transparent. Could you tell me how I could alter the reboot part of the script so that the computer reboots in a set number of seconds?

    Basically, run the script, it renames the computer, but then it shuts down in say 10 hours automatically, basically doing the needed reboot after hours. Is this possible?

    • Hey Marshall,

      i had some issues with accessing our DFS shares after renaming the computer without booting it instantly, but maybe it was an side effect because i have tested different things at the same time with my box. I would recommend that you strip out the reboot line from the script and rename a computer and check file system access. If this is no problem you could wait until the users boots his computer at the end of the day (if this happens at all).

      But to come back to your question. It is possible to do this in many different way, but you have to tell me more about your situation. Is the computer rebootet once a day? What Windows version do you use? What version of powershell is installed? Have you activated powershell remoting (WinRM)?

      I think the easiest way is to do it via the shutdown command (shutdown.exe). Just open a connection (eg. mounting the admin$ share) to the target computer after renaming and fire the shutdown command with x minutes delay.
      Another idea is to fire the shutdown command via WMI by invoking the shutdown process at the remote computer.
      Another one could be: Catch the shutdown event with WMI (Win32_ComputerShutdownEvent) and rename the computer at the users logoff.
      My Favorite one: Rename the computer with Powershell remote, but this has some requirements like activating the WinRM on every computer, which could be a k.o. criteria.

      Let me know if you need some help with this. I think I could get you a working script if you tell me more about your situation.

      Kind regards

  24. Marshall Marshall

    Hey Marco,

    Thanks for the reply, i’ve been working on this today since I posted and this is what i’ve come up with.
    I was getting an error loading AD module running your unedited script, then found out I had to download the remote admin pack for win7. Set that up and that fixed the module loading of AD.

    Then I was getting a “param” unknown function, cmdlet etc… error. After some research I guess it was because param statement has to be the first line in a script. So I moved loading the AD module down, and put the param statement first above it and it worked.

    My solution to the timed shutdown was using pstools. I replaced
    Get-WmiObject Win32_OperatingSystem -ComputerName “$oldComputerName” |
    ForEach-Object {$restart = $_.Win32Shutdown(6)}


    c:\~\desktop\pstools\psshutdown.exe \\”$oldComputerName” -r -t 17:10

    This tells the PC to restart at the exact time given in 24 hour format. So now I can run a script, change the name, and have it reboot at 10PM when I know no one is using the PC, and in the morning it will be like nothing happened to the user. This is because many people do not restart when leaving like we want them to. You have to install pstools from sysinternals for this to work though obviously and use your install path. It works pretty slick! It remains to be seen if it impacts anything like you said being renamed but not restarted as far as accessing things. I will test this.

    • Hey Marshall,

      this is a great solution, thanks for sharing!
      I always forget the Sysinternals tools, because I haven’t worked with these tools (except the analyse tools like procmon, tcpview and procexplorer) in the past. I try to avoid the use of external tools even if it’s possible to do the same thing with on board tools of Windows, but it is often very time consuming.

      It would be great if you could share your experience of renaming the computer and reboot it later the day.

      Btw: I fixed my script and put the param command back to the first line. Thanks for this hint.

  25. Chuck Henson Chuck Henson

    I get an error “win32shutdown privilege not held”. Any help?

    • Hi Chuck,
      Weird, seems to me that you dont have privileges to shutdown the remote computer.
      I found something via google that may help you: http://bit.ly/ZbSCmn

      Can you reply if that worked for you?

  26. Chad Chad

    Please assist this is the error that I get when I run the command. I have the crendentials entered in the script as well. Any help is appreciated.

    PS C:\Users\Administrator\desktop> .\RenameComputer.ps1 -computername “mfe-md-tr
    n1-lt” -newcomputername “NewCompName”
    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
    PS C:\Users\Administrator\desktop>

    • Hi Chad,

      please make sure you used the correct domain name and user account at the user-variable $ADUserName = “ad\myuser”.
      80070005 – Access Denied is returned by the client you want to rename. Maybe you have insufficient rights to do this?
      You can check the remote clients event log for further information.
      Access Denied is a clear return value, the script is working but you do not have enough rights to complete the action.

      Keep me informed what the problem was, or if you haven’t solved your problem,
      Kind Regards,


  27. Chad Chad

    Thanks for such a fast reply.

    I am using my domain admin account for testing I have changed the vaules but it looks like


    the mfe is my domain
    administrator – user account

    Thanks again….

  28. Chad Chad


    It looks like it was a computer issue in the beginning. I had to dejoin the computer and then rejoin and then run your script and it worked. I am not sure what was wrong with the computer but it completed succesfully

    Thanks for all your hard work……

  29. Seb Seb

    Hi Marco,

    I want to know if this script can be run from an SCCM/MDT Task Sequence by adding a “Run PowerShell Script” MDT Task ?

    Best Regards,

    • Can you explain what you want to do?
      I think you could do that, because wmi is running during a task sequence.

  30. Seb Seb

    In fact, I want to rename the computer (WMI-level + AD-level) which is already in the domain just before the end of the Task Sequence because renaming it earlier in the TS results in some problems with USMT restore state (USMT won’t restore because the computer name is not the same…).

    Here is what I plan to do:
    -Creating a new device variable named “NewOSDComputerName” and input the new computer name in it,
    -Create a group named “Rename Computer” which only runs if the TS variable “NewOSDComputerName” exists,

    In this group, I will do the following in my freshly deployed Windows 7:
    -1. Install the RSAT and enable the AD PowerShell Module,
    -2. Call my MDT Toolkit Package with your beautiful script in it, 😉
    -3. Set the PS ExecutionPolicy to Unrestricted,
    -4. Run your script (modded with the needed authentication stuffs + the Import of the MDT Task Sequence Module) with these parameters $ENV:COMPUTERNAME & $TSENV:NEWOSDCOMPUTERNAME,
    -5. Restart the computer,
    -6. Set PS PolicyExecution back to Default,
    -7. Uninstall or unconfigure RSAT.

    What do you think about it ?

    Best Regards,

    • After thinking about your idea last night, I came to the question “why doesn’t he deploy the computer with the correct name?”. I think the answer is, that you replace an existing computer for example “MyOldComp” to solve your USMT name matching problem and rename it afterwards. Is that right?

      I think you could do it like you described, but I don’t know if you have to rename the computer AD object as well to match the computer account names at logon time. My script doesn’t rename the AD object, because the computer does it at the renaming process.
      If my script is running within a TS on a local machine you can get rid of some remote code execution and checks if the computer is online.

      Another idea: A workaround for RSAT installation and AD modules could be to lookup the DNS if a computer with the name “$TSENV:NEWOSDCOMPUTERNAME” is already registered or not. Also pay attention to your DNS entries and delete old objects, after you renamed a computer. We have enabled zone aging and scavenging to clean up any missed renamed computer from our DNS :).

      Hope my comment was helpful.

      Let me know if you have any questions.

      Best Regards,

  31. Seb Seb

    No, in fact I forgot to mention that we are using a Refresh scenario launched by a logged user from the Software Center, so we are reimaging and restoring USMT captured data on the same machine…

    Fianlly, I setup what I imagined in my Task Sequence and it’s working great, all is updated: computer name (@WMI-level & AD-level) and DNS is fine too (we also enabled scavenging processes on our DNS :D).

    So I think, we’ll do that way…

    Thank you for the time you gave me and for the sharing of your great work on this script.

    Best regards,

    • I’m glad to hear that your task is running! Thanks for your explanation, maybe someone else has the same szenario and get some inspiration from your idea.

      Best Regards

  32. Seb Seb

    Hi Marco,

    An easiest way to do the trick in my TS was to install WMF 3.0 (PowerShell 3.0) which includes the Rename-Computer command-let ! 😉

    If you are interested I can share you the PS script I made to run in a TS.

    Best regards,

    • It would be great if you could share your script. Maybe we can use it (or someone else) when we get into such a situation :).
      Thank you again for your reply

      Best regards,

  33. Seb Seb

    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,

  34. shawn shawn

    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 ?

  35. mmmh…
    why not…

    $computers = Get-adcomputer | where {$_.name –like “*”}
    $num = 0
    Foreach($computer in $computers)
    For($num=1;$num –lt $computers.count;$num++)
    echo Rename-computer –computername $computer –newname “s-$num” –domaincredential domain\user –force –restart

    • True, but the computer rename function was implemented in Powershell v2 or v3. At the time I worte this post, this was not available

  36. Duke Duke

    The script works great. Do you have any suggestion on how you would prompt the user executing the script to provide SmartCard and PIN credentials when the script is run? This assumes the SmartCard is currently in use by the person running the script..

    Any help would be greatly appreciated


Schreib einen Kommentar

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