Join computers to the domain using a script

I have a text file with a list of computers that are Not joined to the domain.
I need a script that join each comuter from the list to the domain and reboot it.

Thanks
jskfanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael PfisterCommented:
Take a look at netdom.exe (comes with Windows resource Kit)
NETDOM JOIN machine /Domain:domain [/OU:ou path] [/UserD:user]
           [/PasswordD:[password | *]]
           [UserO:user] [/PasswordO:[password | *]]
           [/REBoot[:Time in seconds]]

NETDOM JOIN Joins a workstation or member server to the domain.

machine is the name of the workstation or member server to be joined

/Domain         Specifies the domain which the machine should join. You
                can specify a particular domain controller by entering
                /Domain:domain\dc. If you specify a domain controller, you
                must also include the user's domain. For
                example: /UserD:domain\user

/UserD          User account used to make the connection with the domain
                specified by the /Domain argument

/PasswordD      Password of the user account specified by /UserD.  A * means
                to prompt for the password

/UserO          User account used to make the connection with the machine to
                be joined

/PasswordO      Password of the user account specified by /UserO.  A * means
                to prompt for the password

/OU             Organizational unit under which to create the machine account.
                This must be a fully qualified RFC 1779 DN for the OU.
                If not specified, the account will be created under the default
                organization unit for machine objects for that domain.

/REBoot         Specifies that the machine should be shutdown and automatically
                rebooted after the Join has completed.  The number of seconds
                before automatic shutdown can also be provided.  Default is
                30 seconds

Windows Professional machines with the ForceGuest setting enabled (which is the
default for machines not joined to a domain during setup) cannot be remotely
administered. Thus the join operation must be run directly on the machine
when the ForceGuest setting is enabled.


-----------------------------------------


a simple batch woulk look like:

for /f %%a in (computer.txt) do netdom join %%a ...



0
jskfanAuthor Commented:
for /f %%a in (computer.txt) do netdom join %%a ...
would this command join computer and reboot?
0
Michael PfisterCommented:
If you look on the parameters of netdom, it can do a join and a reboot.
The "for" command will go through your list of computers and execute the netdom for each computer.
Of course it gets more complicated if the unjoined target computers have different local admin credentials (passed by /UserO and /PasswordO)
0
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

jskfanAuthor Commented:
First I will install a domain controller, create an adminstrator domain account.
The local admin account in each machine is the same as the Admin account.


In this case I will write the machine names in a text file, one name per line.
and write the script:
for /f %%a in (computer.txt) do netdom join %a /Domain:MydomaonName /OU:ComputersOU /User:Administrator /Password:adminpassword /Reboot

Correct?
0
Michael PfisterCommented:
You need to specifiy the Domain user and the local user, see atached code snippet
Note that in a batch you need to use %% in a for loop, on the command line  a single % is enough.
for /f %%a in (computer.txt) do netdom join %%a /Domain:MydomainName /OU:ComputersOU /UserD:Administrator /PasswordD:adminpassword /UserO:Administrator /PasswordO:adminpassword /Reboot

Open in new window

0
jskfanAuthor Commented:
so the first userD and passwordD are domain administartor username and password, the second userO and passwordO are the local admin username and password. Correct?
in this case they don't have to be the same. Correct?
0
jskfanAuthor Commented:
it's hard to pinpoint the source of the error when you use 2 user names and 2 passwords, I get this error:

Logon Failure: unknown user name or bad password

0
jskfanAuthor Commented:

for /f %%a in (c:\computers.txt) do netdom join %%a /domain:mydomain.com /userD:abcd /passwordD:abcd2009! userO=abcd /passwordO=abcd2009!!/ Reboot





0
jskfanAuthor Commented:
any updates??
0
Michael PfisterCommented:
Your post shows 2 poblems: no slash / before userO and no space between abcd2009!! and /Reboot

Are you using the build in domain admin for UserD or did you create it yourself?
Have you checked that you are able to log on as local admin to the workstation with your UserO and PasswordO credentials?

Another check would be: copy netdom.exe to one of your workstations. Log in as local admin and run the netdom command WITHOUT UserO and PasswordO.

Also please post what version/date/timestamp your netdom.exe is.
0
jskfanAuthor Commented:
I am running the netdom just for one workstation and it still gives me sysntax error.

Netdom join \\mywin2kstation /Domain:1.com /UserD:admin1 /PasswordD:* UserO:admin1 /PasswordO:* /reboot:15
0
jskfanAuthor Commented:
how do check the version of Netdom.?
is there any simple command of Netdom join to run on just one computer and see from there how it joins a computer to the domain, and from there I will try the script.
thanks
0
Michael PfisterCommented:
Right click on the netdom.exe and choose properties -> version. Should be netdom5.

Simple command:

Netdom join XPWSName /Domain:DOMAIN  /UserD:admin1 /PasswordD:* UserO:admin1 /PasswordO:* /Reboot
0
jskfanAuthor Commented:
it's 5.2 version
0
jskfanAuthor Commented:
I get this:

The syntax of this command is:

NETDOM [ ADD | COMPUTERNAME | HELP | JOIN | MOVE | QUERY | REMOVE |
         MOVENT4BDC | RENAMECOMPUTER | RESET | TRUST | VERIFY | RESETPWD ]
0
jskfanAuthor Commented:
I may just need a VBScript that will join  computersto the domain.
Do you know of any?
0
Michael PfisterCommented:
I've never seen a VBScript to do this and I'm currently using netdom.exe to join XP workstations without any problems.
But looking at my previous post either EE or I missed a slash. This is probably causing the syntax error. So look at
netdom help join
and make sure all optional parameters are preceeded with a slash.

The only parameters without slash (/) is JOIN and the computer name. I try again in the code snippet window.
XPWSName must be replaced with your workstaions computer name
DOMAIN with the Netbios Domain Name (I've not tried it with the full qualified domain name)

Also important: do not call Netdom.exe with a preceeding directory name, like
C:\Tools\netdom join ....
This confuses the command line parser of netdom.exe. Change to the directory where netdom.exe resides before you call netdom.exe, i.e.
cd\Tools
netdom join....

Hope this works...
Netdom join XPWSName /Domain:DOMAIN  /UserD:admin1 /PasswordD:* /UserO:admin1 /PasswordO:* /Reboot

Open in new window

0
Michael PfisterCommented:
Google came up with this script. I've never tried...
http://techtasks.com/code/viewbookcode/1642
0
jskfanAuthor Commented:
This script does it..
I wonder why it doesn't reboot the machine or prompts for reboot.
I also need someone to modify it so that it can read from a text file a computer name and join it to the domain then go to next computer name in the list
0
Michael PfisterCommented:
I've added some code to read a text file and reboot the target afterwards.
Imortant: I haven't tested this code (no test environment available here), so there may be some errors

HTH
' This VBScript code joins a computer to a domain.
 
' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' ISBN: 0-596-00466-4
' ---------------------------------------------------------------
 
' ------ SCRIPT CONFIGURATION ------
strDomain       = "<DomainName>"        ' e.g. rallencorp.com
strDomainUser   = "<DomainUserUPN>"     ' e.g. administrator@rallencorp.com
strDomainPasswd = "<DomainUserPasswd>"
strLocalUser    = "<ComputerAdminUser>" ' e.g. administrator
strLocalPasswd  = "<ComputerUserPasswd>"
strComputerList = "<Text file with computer names>"
 
' ------ END CONFIGURATION ---------
 
'########################
' Constants
'########################
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 ForReading = 1
 
 
'#####################################
' Open and read text file line by line
'#####################################
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(strComputerList, ForReading)
Set objWMILocator = CreateObject("WbemScripting.SWbemLocator")
objWMILocator.Security_.AuthenticationLevel = 6
 
Do Until objTextFile.AtEndOfStream
	strComputer = objTextFile.Readline
	WScript.Echo "Trying to join " & strComputer & " to " & strDomain
	
	'###########################
	' Connect to Computer
	'###########################
	
	set objWMIComputer = objWMILocator.ConnectServer(strComputer,  _
	           		                       "root\cimv2", _
	                                                 strLocalUser, _
	                                                 strLocalPasswd)
	set objWMIComputerSystem = objWMIComputer.Get( _
	                               "Win32_ComputerSystem.Name='" & _
	                               strComputer & "'")
	
	'###########################
	' Join Computer
	'###########################
	rc = objWMIComputerSystem.JoinDomainOrWorkGroup(strDomain, _
	                                                strDomainPasswd, _
	                                                strDomainUser, _
	                                                vbNullString, _
	                                                JOIN_DOMAIN)
	if rc <> 0 then
	    WScript.Echo "Join failed with error: " & rc & " for computer " & strComputer
	else
	    WScript.Echo "Successfully joined " & strComputer & " to " & strDomain & ", now rebooting..."
	    set objWMIComputerSystem = objWMIComputer.Get("Win32_OperatingSystem")
	    For Each objOS in objWMIComputerSystem
		If objOS.Primary = True Then
			objOS.Reboot()
		End If
	    Next
	End If
	Set objWMIComputerSystem = Nothing
    	Set objWMIComputer = Nothing
    	
Loop
WScript.echo "Done"

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jskfanAuthor Commented:
something wrong at the line below:

set objWMIComputer = objWMILocator.ConnectServer(strComputer,  _
                                                    "root\cimv2", _
                                                       strLocalUser, _
                                                       strLocalPasswd)

when I run the script from the DC to join a remote computer to the domain, I receive error: Access Denied
when I run the script from the computer itself that needs to be joined to the domain I receive error: User credentials can't be used for local connections.

and both error point to the line of code I posted above.
0
Michael PfisterCommented:
Hm, but I didn't touch that part of the script. Why did it work before?
0
jskfanAuthor Commented:
the one I tried and worked is the one below:
I run it on a local computer it joined it to the domain, but didn't reboot it. I rebooted it manually.

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
 
strDomain = "domainname"
strPassword = "!password"
strUser = "Administrator"
 
Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName
wscript.echo strcomputer
Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & _
    strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & _
        strComputer & "'")
 
ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, _
    strPassword, strDomain & "\" & strUser, NULL, _
        JOIN_DOMAIN + ACCT_CREATE)
0
Michael PfisterCommented:
You version does not use the remote workstaions local account. Hm sorry, I have no idea except that the credentials must be wrong.
0
jskfanAuthor Commented:
do you mean this version of NETDOM 5.2 version, can't join remote computer to the domain?
if so, I can download a new version.
0
Michael PfisterCommented:
No, I meant you version of the vbscript.
I'll check if I can test the remote join function of netdom 5.2. I never did it this way I always use netdom to join the domain from the workstation.
0
jskfanAuthor Commented:
strDomain   = "DomainName"
strPassword = "AdminPassword"
strUser     = "administrator"
 
Const ForReading = 1
Const ForWriting = 2
Const JOIN_DOMAIN             = 1
Const ACCT_CREATE             = 2
Const ACCT_DELETE             = 4
Const DOMAIN_JOIN_IF_JOINED   = 32
Const JOIN_UNSECURE           = 64
Const DEFERRED_SPN_SET        = 256
Const INSTALL_INVOCATION      = 262144
 
set wshshell = createobject("wscript.shell")
Set objNetwork = CreateObject("WScript.Network")  
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objlist = objfso.OpenTextFile("c:\list.txt", ForReading)
Set objlog = objfso.CreateTextFile("c:\log.txt", ForWriting)
 
Do Until objlist.AtEndOfStream
strComputer = objlist.ReadLine

wscript.echo strcomputer
If Reachable(strComputer) Then
Set objComputer = GetObject("winmgmts:" & "{impersonationLevel=impersonate, authenticationLevel=pktPrivacy}!\\" & _
    strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" _
    & strComputer & "'")
ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, _
   strPassword, _
   strDomain & "\" & strUser, _
   NULL, _
   JOIN_DOMAIN+ACCT_CREATE)
 
if ReturnValue <> 0 then
    objlog.WriteLine "Join failed with error: " & ReturnValue
else
    objlog.WriteLine "Successfully Joined " & strComputer
end if
 
wshshell.run "shutdown /r /m \\" & strComputer
Else
objlog.WriteLine strComputer & " Not Reachable !"
End If
Loop
 
Function Reachable(strComputer)
 strCmd = "ping -n 1 " & strComputer
 Set objShell = CreateObject("WScript.Shell")
 Set objExec = objShell.Exec(strCmd)
 strTemp = UCase(objExec.StdOut.ReadAll)
 
 If InStr(strTemp, "REPLY FROM") Then
 Reachable = True
 Else
 Reachable = False
 End If
End Function
 

It worked just fine...... Joined the computer to the domain and reboot the computer.
The problem was when running the script from the DC against  the target  computer, it throws error.
when I run it from a different computer which is also member of the domain it works just fine.



0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.