'****************************************************
'		Script Witten by Larry Heintz
'		September 2006 www.windowsadminscripts.com
' This script will add a computer to an Active
' Directory Forest. This will save time when adding
' multiple computers to an Active Directory Forest.
'
' Script Usage:
' joinAD.vbs /computer:[computername]
' /domain:[Active Directory Domain]
' /adminu:[AD Admin Username]
' /adminp:[AD Admin Password]
'****************************************************
Dim args,computername,ad,adminu,adminp
Set args = Wscript.Arguments.Named
computername = args.Item("computer")
ad = trim(lcase(args.Item("domain")))
adminu = trim(lcase(args.Item("adminu")))
adminp = trim(lcase(args.Item("adminp")))

if computername = "" then
	computername = getComputer()
else
	computername = computername
end if

if wscript.arguments.count = 0 then
	Call usage()
elseif ad = "" or adminu = "" or adminp = "" then
	Call usage()
elseif args.exists("domain") and args.exists("adminu") and args.exists("adminp") then
	Call addtoDomain(ad,adminu,adminp,computername)
else
	Call usage()
end if

Function addtoDomain(ADomain,AUser,APassword,ComputerName)
Dim objComputer,ReturnValue
Const JOIN_DOMAIN = 1
Const ACCT_CREATE = 2

Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & ComputerName & "\root\cimv2:Win32_ComputerSystem.Name='"& ComputerName & "'")
	ReturnValue = objComputer.JoinDomainOrWorkGroup(ADomain,APassword,ADomain & "\" & AUser,NULL,JOIN_DOMAIN + ACCT_CREATE)
    if ReturnValue = 0 then
		wscript.echo computername & " has been successfully added to " & adomain & " Active Domain Forest." _
					& " Please reboot the computer now to finish"
	else
		wscript.echo "Please re-run script. The information you entered are incorrect."
	end if
Set objComputer = nothing
End Function
    
Function getComputer()
	Dim objNet
	Set objNet = WScript.CreateObject("WScript.Network") 
	getComputer = objNet.ComputerName 
	Set objNet = Nothing 
End Function

Function usage()
	wscript.echo "Script Usage:"
	wscript.echo "joinAD.vbs /computer:[computername] /domain:[Active Directory Domain]" _
	& " /adminu:[AD Admin Username] /adminp:[AD Admin Password]"
	wscript.quit
End Function
