VBScript to join computers to domain, with specific user and avoid having to manually place them in AD

The following script was used for automatically joining alot of computers to an Active Directory domain, it was required to place the computer in a specific Organizational Unit and also to run with a specified user with only permissions to add machines in this OU and the default new computers OU (giving it unlimited join domain permissions).

So here is a cleaned up short script to join a machine to a domain, using a script specified user (could be changed easily to current user) and place the machine in a specific OU, great for running for specific departments, so You avoid having to manually sort the machines in the end.

Get the txt file with the script here.

On Error Resume Next
' This script joins the current computer to a domain, using specified user and placing it in specified OU
' Created by Sole Viktor - sole@sole.dk

' Set theese variables
strDomain = "mydomain.local" ' Domain to logon
strPassword = "MyPassword" ' Service account logon password
strUser = "MyUserAccount" ' Service account
strOU = "OU=LetsPlaceItHere,OU=MySecondOU,OU=MyFirstOU,DC=mydomain,DC=local" ' OU to place computer in

' Constants to choose from when joining
Const JOIN_DOMAIN = 1
Const ACCT_CREATE = 2
Const ACCT_DELETE = 4
Const WIN9X_UPGRADE = 16
Const DOMAIN_JOIN_IF_JOINED = 32
Const JOIN_UNSECURE = 64
Const MACHINE_PASSWORD_PASSED = 128
Const DEFERRED_SPN_SET = 256
Const INSTALL_INVOCATION = 262144

Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName

' Join Domain
Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & _
strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & _
strComputer & "'")
ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, _
strPassword, strDomain & "\" & strUser, strOU, _
JOIN_DOMAIN + ACCT_CREATE + DOMAIN_JOIN_IF_JOINED)

Select Case ReturnValue

Case 0 Status = "Success"

Case 2 Status = "Missing OU"

Case 5 Status = "Access denied"

Case 53 Status = "Network path not found"

Case 87 Status = "Parameter incorrect"

Case 1326 Status = "Logon failure, user or pass"

Case 1355 Status = "Domain can not be contacted"

Case 1909 Status = "User account locked out"

Case 2224 Status = "Computer Account allready exists"

Case 2691 Status = "Allready joined"

Case Else Status = "UNKNOWN ERROR " & ReturnValue

' Show Status
WScript.Echo "Join domain status: " & Status

End Select

Enjoy and feel free to use it as You please!

55 Responses to “VBScript to join computers to domain, with specific user and avoid having to manually place them in AD”

  • Hi! I just wanted to say thank you for what you’ve published. Your published code on uninstalling the Novell client and ZenWorks have been a huge help, in addition to this code here. So, thanks again 🙂

  • Sole:

    Thanks for the comment 🙂 glad it was usefull

  • Troy:

    KACE (the AppDeploy.com people, now part of Dell) distribute a similar script to this as a sample with their KBOX appliance. Works great, although I’d suggest to them (and you) another error code to add to your ReturnValue case statement, as Googling “2242” and “JoinDomainOrWorkGroup” currently returns no useful information.

    Case 2242 Status = “User account has expired password”

    Not that it’s ever happened to me, of course. 🙂

    Thanks for posting this.

  • anitallica:

    Great, thanks! Worked like a charm.

    One note: at least for me, it only showed the correct status if I put the
    WScript.Echo Status
    line at the end. Otherwise it would show no value.

    Thanks for the script!

  • Jay:

    Thanks! Worked like a charm, with Win XP. I also had to put the
    WScript.Echo Status line
    at the end.

    Should this work with Win 7 as it isn’t for me which I ideally I need it to? Any help would be greatly appreciated. I’m getting “Access denied” which is Error 5.

  • Jay:

    Hi All.Regarding my earlier post. The issue has been resolved, I had to run powershell as an Administrator.

  • Sole:

    Hi Jay,

    Happy you found the error so quickly and thanks for sharing it back.

    -Sole

  • Thomas:

    thanks for sharing!

  • Serge:

    Hi, This might be a dumb question, but how would I use this code? I have about 300 VMs (using VM Player) on hosts that need to be joined to domain. If not this code can you please suggest another way to accomplish what I need to do?

    Thank you in advance.

  • Joe Orlando:

    I tried this with windows 7 and I just get a prompt that says “join status:” and nothing after that. No message at all 🙁

  • Sole:

    Hi Joe,

    Seems the output of status was somehow moved to the start of the script, when it should be at the end?
    Try the code from the page now and see if it helps?

    -Sole

  • Sole:

    You edit the script to your liking including account with ability to join multiple computers and execute it on the machines as a local administrator.
    This could for example be accomplished by adding the script to a GPO that is run on all your 300 servers if they were in a domain 🙂
    If they are not, you will need some other way of executing the script on all your servers. This could be by remotely calling the script with psexec.
    Sorry I won’t be able to give you better suggestions without going into higher details of your specific system.

    -Sole

  • dinesh ingle:

    D:\Dinesh>”Domain Join.bat”

    D:\Dinesh>’ This script joins the current computer to a domain, using specified
    user and placing it in specified OU
    ”’ is not recognized as an internal or external command,
    operable program or batch file.
    The syntax of the command is incorrect.

    Need help!

  • Lars Fredrik Bach:

    I can’t get it to compile. Maybe there’s a problem with my copy/paste.
    Could you please put out a ready .vbs.

    I would be grateful!

  • Sole:

    the script should be run as a VBScript, so ending of file would be .vbs

  • Kevin:

    Sorry, the script dosen’t appear to copy and paste properly directly from the web page, I get script errors on line 4 and then vbscript compilation errors, could you please place a .txt version as you have on some of your other scripts?
    Thanks

  • ditto:

    Lars Fredrik – likely because you pasted the quotes into your script. When you do that it pastes a different ascii character than chr(034). RETYPE the quotes in the script you pasted and likely that will fix it.

  • Sole:

    Done 🙂

  • KY:

    Will this script work if the workstation is already on another domain? and i want to join it to a new domain.

  • Sole:

    Yes, that should not be a problem.

  • MI:

    Hi I’ve run into an issue where the script will only run if I run it from a command line as the administrator. For example right click cmd run as administrator , cd to the directory and run, works fine. The strange thing is the account I’m currently logged in with is already an administrator so I shouldn’t have to manually specify run as administrator. Any ideas?

  • Sole:

    Your computer protects you from running normal programs with unneeded admin rights, so yes you will need to select run as administrator or turn off the UAC security feature.

  • MI:

    Thanks Sole. We ended up running this from Novell startup scripts and worked great. Thankfully UAC has been disabled on all the machines so far.

  • RT:

    The script is working fine but its not returning any value like success or missing OU ..

  • Hari:

    Not Working, this script for connect workgroup to domain ?

  • alok:

    is there a way that I can run these against set of servers listed in a csv file.

    Actually I am looking for a way to provide a csv with 3 columns and the script gets its input from the csv file. An example of the csv:

    Column1 Column2 Cloumn3
    HostA abc.com OU=a,OU=prod,DC=ABC,DC=com
    HostB abc.com OU=a,OU=preprod,DC=ABC,DC=com
    HOSTC pqr.com OU=a,OU=prod,DC=PQR,DC=com

    Can it take hosta and join it to abc.com and move it to OU a.prod.abc.com and HostB to abc.com and move it to OU a.preprod.abc.com?

  • Sole:

    I don’t see why you wouldn’t be able to change the script to do that.

  • alok:

    That’s good to know Sole! I am not a scripting guy so any pointers or help will be appreciated.

    Thanks

  • NetCat:

    Thanks for the script, worked fine for me to work around a pretty unknown MDT error. Thanks again!

  • tcclis:

    I have got the status = 5 “Acces denied” I can’t understand why?

  • Andy:

    Can someone confirm if this is working for Windows 7 please?

  • Tom:

    Seems to work when run elevated in command prompt, but NO status message shows. I have the code with the “wscript.echo” command at the bottom, but no messages……. Any ideas?

    Before I sent this I looked at the script again. The “wscript.echo” command needs to be outside of the Case/Select…

    Works great now….

  • Andy:

    Through the combination of reviewing several websites, and struggling with the calling PowerShell properly with a batch file, I have finally had success. I would like to share my results with all. Good luck. P.S. I have two batch files, one for being one site and one where I join a computer through VPN.

    Step 1 – Include the following in your batch file. This will call the Powershell with proper permissions:

    c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned

    Step 2 – Make the following PowerShell file and make sure to give it the name you entered in the batch file. Replace my all caps items with your information.

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Scope Process
    add-computer -domainname ENTER FQDN HERE -OUPath “OU=kids Laptops,OU=Computer Lab,DC=DOMAIN,DC=DOMAIN,DC=com” -credential (New-Object System.Management.Automation.PSCredential (“DOMAIN\USER”, (ConvertTo-SecureString “PASSWORD” -AsPlainText -Force)))

  • Ganesh Prakasam:

    I don’t have local administrator password to the workstation.

    How do I join the workstations to domain without local admin password via Script.

  • Andre:

    Hi, we just created a new Admin-Image for our Windows 2012 Servers which will be deployed soon. As we would like to join our servers automatically to our domain and place them into a certain OU, we would like to use a script to do so. The Server Name is already given during installation. For Example: STSTE001 or SPSFS001. Now we have different OU’s: Test, Production etc.
    Our Second letter in the Server-Name should indiciate in which OU the server should be placed. I found DJOIN.EXE but did not find a good example how to add servers automatically to a certain OU regarding their Server-Name. Does anybody have a good example how to do so? Any help would be great. Thanks

  • Sole:

    You should be able to edit the script to work like that pretty easy, this string sets where to place the machine. strOU = “OU=LetsPlaceItHere,OU=MySecondOU,OU=MyFirstOU,DC=mydomain,DC=local” ‘ OU to place computer in

  • Andre:

    Hi Sole, thanks for your quick reply.
    What we need is a if-clause. Just for example:
    If the server name is SPSFS001 it needs to be moved into the OU Production. If the server name is STSTE001 it needs to be moved into the OU Test and if the server name is SMSME001 it needs to be moved into the OU Management.
    As I am not relly familiar with VB-Script and Scripts in general a hint into the right direction would be helpfull.
    Thanks in advance

  • Tony G:

    Hi
    I’m having an issue with the above script. It keeps throwing a unknown error 1791 and then Error 234.
    What I’m trying to do is join the W7 PC to a domain but NOT an OU.
    Do i need to replace the username, domain info and PW with my specific info? If so, I’m running into errors even if I don’t modify it to my info.
    Any suggestions?

  • Anonymous:

    Hi, I am quite new to Scripting and Technology. Can you explain in simple terms what are causes for a server to go out of the domain. Sometimes i see servers going out of the domain and the SystemEngineer will add it back

  • Vikash:

    Hi Sole

    Thanks for sharing the script.

    When we are trying to run the script on new system. I have received Access denied message.Please let me know why we have received this type of message. Can we resolve ASAP.

  • Sole:

    Most likely cause would be permissions on local system you will need administrator and in the domain user you will need permission to join the machine to the domain.

  • sathya:

    Urgent :

    Guys please give me a script for “win.net” . i have a domain controller with dc.win.net . i have to join 500 workgroup machine into domain , where i have to run this script ? how to run this script ? Please share any one urgent ********Thanks In Advance*********

  • Sole:

    You should be able to run the script on the 500 workstations, either directly manually, remote execution if you have access to that, scheduled or login scripts, etc.
    I am sorry, but I can’t explain or help further on how to execute a VB Script, I would suggest you google that.

  • Joe:

    Hi Sole

    This is exactly what I am looking for. I have to migrate several hundred computers from our old Domain to a new Domain. I’ve copied the script into notepad, changed all variables to match our environment and saved as VBS file. Run the script and I get no error messages or prompts. What am I doing wrong?

  • Thank you very much for sharing this script.

    I am trying to use it in the base of automated domain join with automated OU placement – we have about 30 different OUs with various GPO applying.
    I am wondering if I could define computer object from W32_Computersystem.Name query, but the main question is how to make it join desired OU based on that name…

    Best Regards

  • Tony G:

    I found that with this script it will join it to the domain and you have to manually reboot the PC. You can change the script to however you want though. The above script works for Windows XP and Windows 7
    I use another script that does everything for me which is for Windows 7.

    $domain = “domain.com”
    $password = “password for user joining domain” | ConvertTo-SecureString -asPlainText -Force
    $username = “$domain name\user with authorization”
    $credential = New-Object System.Management.Automation.PSCredential($username,$password)
    Add-Computer -DomainName $domain -Credential $credential
    Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Restricted -Force

    I saved this as a power shell or .ps1 extension and then created a batch file with the following info. All of this info is on my jump drive so that’s why there is multiple drive letters. Normally you would just have the drive letter associated with the jump drive but it sometimes changes so with this configuration, it finds all possible drive letter connections. If it doesn’t you will see errors but that’s normal because it’s trying to find info of a drive letter for the jump drive that is not connected. If you wanted to you don’t have to put in all those drive letters but like I said, it sometimes look for other drive letters.

    powershell -command “”
    powershell -file e:\domainjoin.ps1
    powershell -file f:\domainjoin.ps1
    powershell -file g:\domainjoin.ps1
    powershell -file h:\domainjoin.ps1
    powershell -file i:\domainjoin.ps1
    powershell -file j:\domainjoin.ps1
    powershell -file k:\domainjoin.ps1
    powershell -file l:\domainjoin.ps1
    powershell -file m:\domainjoin.ps1
    powershell -file n:\domainjoin.ps1
    powershell -file o:\domainjoin.ps1

    shutdown /r /t 2 Save all contents in a .bat file.

    Basically you run the .bat file and it joins the computer to the domain by getting the info off the powershell or .ps1 file. After that it reboots my PC and when it comes up, it’s joined to the domain.

  • Riaad:

    Hi, I am getting join domain status = UNKNOWN ERROR 2202, can someone please assist

  • Gregg:

    Is there a modification that would allow this to join computers that already exist in AD (such as a computer refresh scenario). We refresh yearly but the machine names stay the same and this won’t rejoin if an account already exists.
    Thanks,
    Gregg W.

  • Ajishlal:

    Hi
    I am getting UNKNOWN STATUS 1791 while joining to domain from a Win 7 machine and “wscript.echo” command at the bottom, but no messages showing even if i enter either wrong password or user id.
    I would be great full

  • Jay:

    Hi Sole, thanks for making this script.

    I got it to work once, I know I edit the below fields, but I attempted it so many times with various combinations that I’m not sure which one worked. It seems so straight forward, but I’m not sure where I am messing up. Do i enter the information with the quotes or without, such as:
    strUser = “john.smith” ‘ Service account
    or is it
    strUser = john.smith ‘ Service account

    Thank you

    ‘ Set theese variables
    strDomain = “mydomain.local” ‘ Domain to logon
    strPassword = “MyPassword” ‘ Service account logon password
    strUser = “MyUserAccount” ‘ Service account
    strOU = “OU=LetsPlaceItHere,OU=MySecondOU,OU=MyFirstOU,DC=mydomain,DC=local” ‘ OU to place computer in

Leave a Reply