Search code examples
vbscriptdnsworkgroupou

How to join a workgroup computer to a domain remotely


Scenario: I'm using ComputerA in a domain with admin credentials. Remote ComputerB (with known admin credentials) is in a workgroup. ComputerB needs to join a specific domain (Different than ComputerA's) in a specified OU which my active ComputerA credentials have the rights to do. I Cannot use an external program such as NETDOM and would prefer to use VBScript.

Any help is much appreciated!


Solution

  • I was actually able to resolve this on my own. Here's the code for future coders:

    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
    
    Const WbemAuthenticationLevelPktPrivacy = 6
    
    SystemName = "ComputerB"
    strNamespace = "root\cimv2"
    ComputerBLogin= "Login"
    ComputerBPass = "Password"
    ComputerALogin = "Login"
    ComputerAPass = "Password"
    DomainName = "domain.com"
    OU = "OU=desiredou,DC=domain,DC=com"
    
    Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
    
    Set objWMIService = objwbemLocator.ConnectServer(SystemName, strNamespace, ComputerBLogin, ComputerBPass)
    
    objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy
    
    Set colComputers = objWMIService.ExecQuery _
        ("Select * From Win32_ComputerSystem")
    For Each objComputer in colComputers
        ReturnValue = objComputer.JoinDomainOrWorkGroup(DomainName, ComputerAPass, ComputerALogin, OU, JOIN_DOMAIN + ACCT_CREATE)
    Next
    
    If Err.Number <> 0 Then
        Set WshShell = CreateObject("WScript.Shell")
        message = WshShell.Popup ("Unable to join " & SystemName & " to the domain! Please join manually.",, "Error", 0 + 16)
    Else
        Set WshShell = CreateObject("WScript.Shell")
        message = WshShell.Popup ("Domain joining was successful!",, "Success!", 0 + 64)
    End If
    
    Err.Clear