Join Computer to Domain with Desired Computer Name and OU

Active Directory, Windows

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


  • 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 }

      • 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

        • 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 }

  • 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

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

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


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

  • 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?

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

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

    • 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?

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

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

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

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


      • 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

  • 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

Leave a Reply