Join Computer to Domain with Desired Computer Name and OU

Someone submitted a PowerShell request for scripting the adding of a workstation to the domain. The solution was to be used in an imaging process with the ability to change the workstation name and import the workstation into a user specified Organizational Unit with no reboot between steps. I will tackle this request one step at a time taking it from the basics to the user prompt. A small amount of validation is also shown to get you started in handling invalid inputs.

Step #1: This is the simplest method to add a computer to a domain. In this example you will be prompted for credentials followed by the required reboot.

Step #2: If you require an automated script without prompting the user for credentials you can provide the user account with rights to add computers to the domain.

Step #3: The following example shows how to specify the Organizational Unit in Active Directory where the computer account will reside.

Step #4: The following example highlights how you can add a computer to the domain as a new computer name without a reboot in between. Imaging processes may initially assign your computer a random name that requires changing to include a specific naming standard.

Step #5: The final example allows for input from the user to determine both the computer name and the Active Directory location. This utilizes Write-Host and Read-Host with a small amount of IF THEN validation to accomplish this. If someone does not enter any value it will use the Default value as displayed to the user. For the numbers 1-4 option if an invalid character is entered it will also use the specified Default setting.


Step #6: The following is a Function example that can be used within a script or from a GUI compliments from a reader.

Feel free to comment or send me your own scenario that you would like tackled here on PowerShell Blogger.

Print Friendly, PDF & Email


  1. Pingback: Join Computer to Domain with Specified Computer Name and OU »

  2. PSUser

    Very nice! If automation is your goal you could also turn this into a function; drop the write-hosts, and/or move your validation up to the top (along with more help info as you see fit. This way if the function is run manually the user/tech is prompted for one of the OUs and it’s not possible to select anything else.
    some similar logic could go in the computername so that if it’s too short, too long, already in use, etc it will fail with the appropriate message to the user.
    And if the function is automated all you need to do is pass a couple of parameters in, maybe from a fancy HTA GUI for your users.

    function Join-Domain {

    [String]$computername = $env:computername,

    [string]$OU = “CN=Computers,OU=Chicago,DC=your,DC=domain,DC=here”
    $renamecomputer = $true
    if ($computername -eq “” -or $computername -eq $env:computername) { $computername = $env:computername; $renamecomputer = $false }

    $credentials = New-Object System.Management.Automation.PsCredential(“yourdomainuseraccountwithjoinpermissions”, (ConvertTo-SecureString “useraccountpassword” -AsPlainText -Force))
    Write-Verbose “Adding $computername to the domain under $OU”
    Add-Computer -DomainName “” -Credential $credentials -OUPath $OU
    if ($renamecomputer -eq $true) { Rename-Computer -NewName $computername -DomainCredential $credentials -Force }

      1. Ethiene Rodriguez

        I know this thread is from last year, but how would i get a sub prompt? The OU’s I need have two sub OU’s

        So if I were to pick 1. Paris, how can I then get say “eiffel tower”, “Notre Dame”

        Thanks in advance I hope you can help

        1. Steve Parankewich

          The easiest is to simply have 1. Paris – Eiffel Tower 2. Paris – Notre Dame. If you truly need a sub menu you can use a nested If statement with the following:

          if ($ou -eq “2”) {
          Write-Host “Please enter your desired sub location [1-2] [Default 1]:
          1. Eiffel Tower
          2. Notre Dame
          $ou = Read-Host

          $validate = $false
          if ($ou -eq “” -or $ou -eq “1”) { $ou = “OU=Computers,OU=EiffelTower,OU=Paris,DC=your,DC=domain,DC=here”; $validate = $true }
          if ($ou -eq “2”) { $ou = “OU=Computers,OU=NotreDame,OU=Paris,DC=your,DC=domain,DC=here”; $validate = $true }

  3. reda

    thanks Steve for your effort

    please i need your help to automate this script for my case i have 400 computers to be joined to a domain and changing the computer name at the same time how can I do this?
    domain name
    thanks in advance

    1. Steve Parankewich

      I will need a little bit more info on this. How is the rollout taking place? I would recommend adding the PowerShell script to your imaging process and tweaking it to meet your naming requirements.

  4. Jase

    Hi Guys

    This is great, thankyou for posting.
    Is there anyone who could post a simple HTA that links with the script? I am looking to do something similar but instead of showing the powershell window, I would like to show a simple HTA with a box for enter computer name and another box for the location (possibly a drop down).

    Idealy I would like to use PS to join the domain like you have listed but based on the first 3 letters of the computer name typed in join specific OUs, for instance if your name name was PAR1234 join the Paris OU, if the computer name was AUS1234 join the Australian OU.. etc but if this is too difficult to do then I could do with a drop down menu with a few locations.

    I will be running this as part of an MDT/SCCM task sequence when building machines.


    1. Steve Parankewich

      I did something similar to this with Sapien PowerShell Studio which allows you to create a form and then set rules based on Prefix etc. You can then package the file as an .exe file and run it. If you would like consulting services to have me create it for you according to your requirements let me know.

  5. Matt

    This looks like a great script, it’s exactly what I want to do with a site rebuild I have coming up.

    One thing I’d like to be able to do is have the script somehow autoname the PC.

    For example, I’ve created my new domain and OU. I’ve added 1 new PC to the OU with the naming convention I want to use (PC name ends in 00-09 then 10 – 19 EG: PC01, PC25 etc).

    Would it be possible for the script to access the OU, read the PC name and increment that name by 1, rename the new PC and add it to the domain and OU?

  6. Matt

    That would be great Steve. I’m new to Powershell, I know just about nothing, but from how you’ve listed the script above I can see how the sections work, it’s a great way to learn.
    Thanks again.

  7. Joe

    hi Steve

    I was wondering can you show me an example how I would show an error if the computer is already added to the domain and prompts the user to press any key to continue with the rest of the script.

    1. Steve Parankewich

      So you would like the script to first check to see if it is in a workgroup but part of a domain. If already domain joined have it display to the user and move on with the rest of the script?

  8. I may be late to this discussion but I really appreciate you putting this script out there it is something I am trying to implement in my company. I am having some issues though and I hope you could help me. I used Step#5 example and it does change the computer name, however it is not adding it the correct ou, it us defaulting to the Computers OU which is the default AD location. I am not sure what Im doing wrong.

    1. Steve Parankewich

      So the key here is the use of Add-Computer -DomainName “” -Credential $credentials -OUPath $ou. Previously you would have set the $ou to “OU=Computers,OU=Paris,DC=your,DC=domain,DC=here”. I would double check that this is the correct OU syntax.

  9. Pingback: Join Computer to Domain with Desired Computer Name and OU – PowerShell Blogger… – DevOps Infographics Resource Center – Programming and IT

  10. Jeff B

    Can this be done using local admin credentials, if the PC is in a workgroup?

    Here’s what I’ve tried that does not work:

    $cred = New-Object System.Management.Automation.PsCredential(“%computername%\ICCadmin”, (ConvertTo-SecureString “ICCbridge0525” -AsPlainText -Force))

    Write-Host “Please enter your desired computer name: [Default $env:computername]:”
    $computername = Read-Host

    $renamecomputer = $true
    if ($computername -eq “” -or $computername -eq $env:computername) { $computername = $env:computername; $renamecomputer = $false }

    $credentials = New-Object System.Management.Automation.PsCredential(“%computername%\ICCadmin”, (ConvertTo-SecureString “ICCbridge0525” -AsPlainText -Force))
    if ($renamecomputer -eq $true) { Rename-Computer -NewName $computername -LocalCredential $credentials -Force }

    I’m running that via Admin PS, and getting “Access Denied” every time. Confirmed user is in local Admin group, UAC is off, and again running via elevated power shell window.

    Any assistance is appreciated.

      1. Jeff B

        That is correct. I’ve got 20 PCs for a customer that (because they don’t want to pay for it) won’t be in a Domain. On my WDS server, I have a base image and an Unattend Answer File that gives the new PC a random name (Desktop-W8MX2T or some such), etc. I’d like to have a prompt that launches on first log in “What would you like this computer to be named?”, I enter the desired name, and it does the rest.


      2. Ivan Navarro

        I would like to get some info from the PC before has been added to the domain, and that info saved into a notecard with the PC name, plus, if the PC can not be added to domain, the notecard won´t be saved.

        PC Name:
        User added:
        Serial PC:
        OU added.

        Can you help me with it Steve?


        Regards from Mexico

  11. TomM87

    Great post! Getting it done in a single reboot took alot of searching. Here are my modifications to the script if this helps anybody (like Jase). It detects whether or not the computer is a laptop or desktop and names it according to our naming convention (company name and LPT or DSK respectively as the prefix followed by the last 6 digits of the serial number) and then adds the Domain Users group to local Administrators (we give our employees local admin rights for running apps elevated). The password for the domain account used to join is an encrypted string stored in “join.crd”. The script itself is kicked off by a batch file bypassing the execution policy and running PS as an admin, so far it has worked fairly well however it sometimes errors out (if machine object already existed in AD for instance). I would like to add error handling if anyone has suggestions they would be greatly appreciated.
    Script: (NameAndJoin.ps1)
    $HardwareType=gwmi win32_ComputerSystem | Select-Object -ExpandProperty PCSystemType
    $SN=gwmi win32_bios | Select -Expandproperty SerialNumber
    $CredPath= $PSScriptroot + “\Join.crd”
    $cred = New-Object System.Management.Automation.PsCredential(“MES****\DomainJoin”, (Get-Content $CredPath | ConvertTo-SecureString -Key (1..16)))
    If ($Hardwaretype -eq 2) {Write-Host “Computer is a Laptop”
    $NewComputername = “MES-LPT-” + $SN.substring($SN.length – 6, 6)
    Write-Host “New Machine Name Will Be: ” $NewComputername
    Add-Computer -DomainName “MES****.COM” -Credential $cred -OUPath “OU=Laptops,OU=Workstations,OU=MESComputers,DC=mes****,DC=com”
    Write-Host “Renaming Computer…”
    Rename-Computer -NewName $NewComputername -DomainCredential $cred -Force
    Write-Host “Adding Domain Users to Local Admins Group…”
    ([adsi]”WinNT://./Administrators,group”).Add(“WinNT://MES****.COM/Domain Users,group”)
    Write-Host “Rebooting Computer…”
    Else {Write-Host “Computer is a Desktop”
    $NewComputername = “MES-DSK-” + $SN.substring($SN.length – 6, 6)
    Write-Host “New Machine Name Will Be: ” $NewComputername
    Add-Computer -DomainName “MES****.COM” -Credential $cred -OUPath “OU=Desktops,OU=Workstations,OU=MESComputers,DC=mes****,DC=com”
    Write-Host “Renaming Computer…”
    Rename-Computer -NewName $NewComputerName -DomainCredential $cred -Force
    Write-Host “Adding Domain Users to Local Admins Group…”
    ([adsi]”WinNT://./Administrators,group”).Add(“WinNT://MES****.COM/Domain Users,group”)
    Write-Host “Rebooting Computer…”

    Batch file to kick it off: (NameAndJoin.cmd)
    PowerShell.exe -NoProfile -Command “& {Start-Process PowerShell.exe -ArgumentList ‘-NoProfile -ExecutionPolicy Bypass -File “”%~dpn0.ps1″”‘ -Verb RunAs}”

    All three files in same directory

  12. David

    I realize this post is aging, but would you be able to adapt this script to allow this to be done remotely/over VPN? To be run locally against a remote computer I mean.

    I know this has some prerequisites services
    Remote Access Auto Connection Manager
    Remote Access Connection Manager
    Remote Procedure Call (RPC)
    Remote Procedure Call (RPC) Locator Remote Registry

    but if possible, it would be nice to see this be able to be run against a computer on the local network, instead of having to be at each physical machine. Thank you!

  13. James

    This ? is not about joining the domain but was wondering if you could help.

    I need to auto make user with admin rights and the username need to be the first 3 of the computer name.

    Example: Computer name ASM196123001
    Username ASM
    Password Password123

  14. Dan

    I am not sure if anyone is still following this thread or not but I am needing help with a simple script file that will add a workstation to the domain and set the computer to login automatically using the domain password.

    To make sure I am clear our students walk up and turn on the computer and it just boots to the desktop with no password prompt and logins in to our domain.

  15. BryanC

    Write-Host “Please enter your desired computer name: [Default $env:computername]:”
    $computername = Read-Host
    $renamecomputer = $true
    if ($computername -eq “” -or $computername -eq $env:computername) { $computername = $env:computername; $renamecomputer = $false }
    Write-Host “Please enter your desired location [1-2] [Default 1]:
    1. Domain Computers
    2. Windows 10 Computers
    $ou = Read-Host
    $validate = $false
    if ($ou -eq “” -or $ou -eq “1”) { $ou = “OU=Computers,OU=Domain Computers,DC=XXXXc,DC=YYY”; $validate = $true }
    if ($ou -eq “2”) { $ou = “OU=Win10-Computers,OU=Domain Computers,DC=XXXX,DC=YYY”; $validate = $true }
    if ($validate -eq $false) { Write-Host “Invalid input, defaulting to [1].”; $ou = “OU=Computers,OU=Domain Computers,DC=XXXX,DC=YYY”}
    $credentials = New-Object System.Management.Automation.PsCredential(“egmc_ntdom\newcomputer”, (ConvertTo-SecureString “passwordABC” -AsPlainText -Force))
    Write-Host “Adding $computername to the domain”
    THESE twoBelow
    Add-Computer -DomainName -Credential $credentials -OUPath $ou
    if ($renamecomputer -eq $true) {Rename-Computer -NewName $computername -DomainCredential $credentials -Force }
    the string is missing the terminator.. i have been staring for a while and ????

    also how do you execute to look like above in ps window.. I need to execute as part of script for pc techs…so they can put in the name and it will add to domain.


    your scripts has great merit..but i am not realy good at this at all…
    your script on last few line constany says :

  16. Alex

    in the commands:

    $credentials = New-Object System.Management.Automation.PsCredential(“yourdomain\useraccountwithjoinpermissions”, (ConvertTo-SecureString “useraccountpassword” -AsPlainText -Force))

    do i leave the quotes and just input my password between the quotes, same for yourdomain\useraccountwithjoinpermissions

    Let me know

    Thank You

Leave a Reply

Your email address will not be published. Required fields are marked *