Join Computer to Domain – Automatically

email me

Dim strUser, strOU, strPassword, strDomain

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")
 
'domain
strDomain = "YourDomain"

'OU
strOU = "PathToOU"
 
'Credentials 
strUser = "Username"
strPassword = "Password"
 
'Computer name
strComputer = objNetwork.ComputerName

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)
 
If ReturnValue = 0 Then
	msgbox "Machine has joined the domain successfully. Please click OK to reboot",64,"Success"
ElseIf ReturnValue = 2224 Then	
	'computer account already exists, attempting domain join
	msgbox "Machine has joined the domain successfully. Please click OK to reboot",64,"Success"
	ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, strPassword, strDomain & "\" & strUser, strOU, JOIN_DOMAIN)
 End If


Notes

Joining a Workgroup

wmic.exe /interactive:off ComputerSystem Where “Name=’%computername%'” Call UnJoinDomainOrWorkgroup FUnjoinOptions=0

wmic.exe /interactive:off ComputerSystem Where “Name=’%computername%'” Call JoinDomainOrWorkgroup name=”Azure”