Zum Inhalt

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


  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

  2. I provide you a working script tomorrow, when im on a computer and not on my iphone 🙂

  3. 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 🙂

  4. Cam Cam

    This requires the AD server to be Server 2008 R2?

  5. 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?

  6. 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.

  7. 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.

  8. 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.

  9. 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

  10. Cam Cam

    I got it, thanks.

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

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

  11. 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.

  12. Ed Ed


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


  13. 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.

  14. 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.

  15. 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

  16. 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!

  17. 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 🙂

  18. 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.

  19. Oh, yes. Try putting this at the top (first line) of the script.

    import-module activedirectory
    More information here: http://blogs.msdn.com/b/rkramesh/archive/2012/01/17/how-to-add-active-directory-module-in-powershell-in-windows-7.aspx

    If that doesn’t work you have to install the „Active Directory Modules for Powershell“ at your server to do this, because my script first gets the object from the active directory, to check if it exists.
    If you want to run this script from your windows 7 box try to comment out the code lines documented at line #32.

    Let me know if that worked for you.

  20. 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!

  21. 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!

  22. 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!

  23. 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!

  24. 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

  25. 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

  26. 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.

  27. 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?

  28. 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

  29. 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.

  30. 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.

  31. 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?

  32. :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

  33. 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?

  34. 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

  35. 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.

  36. 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.

  37. Chuck Henson Chuck Henson

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

  38. 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?

  39. 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>

  40. 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,


  41. 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….

  42. 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……

  43. 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,

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

  45. 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,

  46. 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,

  47. 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,

  48. 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

  49. 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,

  50. 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,

Schreibe einen Kommentar

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

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.