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.

Add-Computer -DomainName "your.domain.here"
Restart-Computer

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.

$cred = New-Object System.Management.Automation.PsCredential("domain\useraccountwithjoinpermissions", (ConvertTo-SecureString "useraccountpassword" -AsPlainText -Force))
Add-Computer -DomainName "your.domain.here" -Credential $cred
Restart-Computer

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

$cred = New-Object System.Management.Automation.PsCredential("domain\useraccountwithjoinpermissions", (ConvertTo-SecureString "useraccountpassword" -AsPlainText -Force))
Add-Computer -DomainName "your.domain.here" -Credential $cred -OUPath "OU=computers,OU=yourlocation,DC=your,DC=domain,DC=here"
Restart-Computer

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.

$cred = New-Object System.Management.Automation.PsCredential("domain\useraccountwithjoinpermissions", (ConvertTo-SecureString "useraccountpassword" -AsPlainText -Force))
Add-Computer -DomainName "your.domain.here" -Credential $cred -OUPath "OU=Computers,OU=YourLocation,DC=your,DC=domain,DC=here"
Rename-Computer -NewName $newcomputername -DomainCredential $credential -Force
Restart-Computer

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.

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-4] [Default 1]:
1. Chicago
2. Paris
3. Sydney
4. Toronto"
$ou = Read-Host

$validate = $false
if ($ou -eq "" -or $ou -eq "1") { $ou = "OU=Computers,OU=Chicago,DC=your,DC=domain,DC=here"; $validate = $true }
if ($ou -eq "2") { $ou = "OU=Computers,OU=Paris,DC=your,DC=domain,DC=here"; $validate = $true }
if ($ou -eq "3") { $ou = "OU=Computers,OU=Sydney,DC=your,DC=domain,DC=here"; $validate = $true }
if ($ou -eq "4") { $ou = "OU=Computers,OU=Toronto,DC=your,DC=domain,DC=here"; $validate = $true }
if ($validate -eq $false) { Write-Host "Invalid input, defaulting to [1]."; $ou = "OU=Computers,OU=Chicago,DC=your,DC=domain,DC=here"}

$credentials = New-Object System.Management.Automation.PsCredential("yourdomain\useraccountwithjoinpermissions", (ConvertTo-SecureString "useraccountpassword" -AsPlainText -Force))
Write-Host "Adding $computername to the domain"
Add-Computer -DomainName "your.domain.here" -Credential $credentials -OUPath $ou
if ($renamecomputer -eq $true) { Rename-Computer -NewName $computername -DomainCredential $credentials -Force }
Restart-Computer

join-domain

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

function Join-Domain {

Param(
[Parameter(Position=0)]
[String]$computername = $env:computername,
[Parameter(Position=1)]
[ValidateSet(“OU=Computers,OU=Chicago,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Paris,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Sydney,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Toronto,DC=your,DC=domain,DC=here”)]
[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(“yourdomain\useraccountwithjoinpermissions”, (ConvertTo-SecureString “useraccountpassword” -AsPlainText -Force))
Write-Verbose “Adding $computername to the domain under $OU”
Add-Computer -DomainName “your.domain.here” -Credential $credentials -OUPath $OU
if ($renamecomputer -eq $true) { Rename-Computer -NewName $computername -DomainCredential $credentials -Force }
}

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

39 Responses

  1. PSUser says:

    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 {

    Param(
    [Parameter(Position=0)]
    #[ValidateScript({})]
    [String]$computername = $env:computername,

    [Parameter(Position=1)]
    [ValidateSet(“OU=Computers,OU=Chicago,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Paris,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Sydney,DC=your,DC=domain,DC=here”,”OU=Computers,OU=Toronto,DC=your,DC=domain,DC=here”)]
    [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 “your.domain.here” -Credential $credentials -OUPath $OU
    if ($renamecomputer -eq $true) { Rename-Computer -NewName $computername -DomainCredential $credentials -Force }
    Restart-Computer
    }

    • Steve Parankewich says:

      Thanks Nick… I have added the function as an additional option!

      • Ethiene Rodriguez says:

        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

        • Steve Parankewich says:

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

      • wayne deshotel says:

        Hello, I used the Step#3 and it worked great. Steve is there a way to add some script commands in Step#3 to automatically remove the current computer from the existing domain using the local admin account and password, then add the same computer to a different domain and reboot ? Or would you have to have 2 reboots?

        • Steve Parankewich says:

          You can join a different domain with 1 reboot as you can simply leave and join another domain without having to go back to a workgroup in between.

  2. reda says:

    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 jedu.com
    thanks in advance

    • Steve Parankewich says:

      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.

  3. Jase says:

    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.

    Regards

    • Steve Parankewich says:

      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.

  4. Laura Keith says:

    Thanks Steve for sharing a nice post and I am feeling lucky to read it.Keep sharing such amazing article in future.

  5. Matt says:

    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 says:

    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 says:

    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.

    • Steve Parankewich says:

      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. Isha says:

    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.

    • Steve Parankewich says:

      So the key here is the use of Add-Computer -DomainName “your.domain.here” -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. Jeff B says:

    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.

    • Steve Parankewich says:

      So your goal is to just rename the computer as a stand alone machine, not domain joined?

      • Jeff B says:

        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.

        Thanks!

      • Ivan Navarro says:

        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.

        Date:
        PC Name:
        User added:
        Serial PC:
        Ram:
        WindowsVersion:
        OU added.

        Can you help me with it Steve?

        Thanks

        Regards from Mexico

  10. TomM87 says:

    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…”
    Restart-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…”
    Restart-Computer
    }

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

    All three files in same directory

  11. David says:

    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!

    • Steve Parankewich says:

      I have not tested it, but you should be able to remotely connect to the machine via PowerShell and execute the same commands.

  12. James says:

    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

    • Steve Parankewich says:

      Are you looking to auto create a local user that is part of the Administrators group on the local desktop?

  13. Dan says:

    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.

  14. BryanC says:

    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 egmc.org -Credential $credentials -OUPath $ou
    if ($renamecomputer -eq $true) {Rename-Computer -NewName $computername -DomainCredential $credentials -Force }
    restart-computer
    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.

    steve,

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

  15. Alex says:

    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

  16. Panelo Pansoy says:

    Hi Steeve,

    I tried the script it work if I manually added the computer name to the right container OU in Active Directory before running the script. Here OU=objects,OU=wkswin10,OU=USWD,DC=Server,DC=Company,DC=ORG

    Is there a script to add the computer to The OU=USWD container

    Thx

    • Steve Parankewich says:

      We would simply need to change the script to create the object first and then join the domain. So we are doing exactly what you are doing manually except automated.

  17. Sumit Patel says:

    This is a wonderful script. I used your script to join my home work machine to my domain and worked perfectly.

  1. October 30, 2015

    […] the domain as well as prompting the user to enter the computer name and location. Head on over to PowershellBlogger.com for the full write up and thanks for everyone’s continued […]

  2. January 28, 2017

    […] Source: powershellblogger.com […]

Leave a Reply to Sumit Patel Cancel reply

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