Solved

Netdom vbscript or batch file

Posted on 2011-09-09
6
1,410 Views
Last Modified: 2012-05-12
I need a script that will prompt for a username and password, then ask for the person to type in a new computername. It will then use netdom to rename the local pc and domain account, and then reboot the machine. I am trying to keep from having to reboot these machines 2 to 3 times to get them back on the name.
0
Comment
Question by:tomtom98
  • 3
  • 3
6 Comments
 
LVL 7

Expert Comment

by:ednetman
ID: 36516081
I have a vb script that should take care of this for you, let me get to work and I'll pull it from my SkyDrive.
~Ed
0
 

Author Comment

by:tomtom98
ID: 36518805
Awesome...When are you able to get that to me?
0
 
LVL 7

Expert Comment

by:ednetman
ID: 36526920
Well, this should get you started......

It actually deletes the account and rejoins it, just need to add the rename portion in.

Look for the variable MyDomain and change that to whatever your domain is.  Also you can hard-code the administrator user ID and password.

In your environment, do you add the computer in Active Directory first, or do you join the domain from the workstation to create the AD account?

Can be run remotely against the machine, needs netdom.exe and psexec.exe in the same folder to work remotely.
'Script Name: ComputerDomainRename.vbs
Option Explicit

Dim strComputerName, StrCompBOS, strPassword, dBug, strBatFile
Dim pathlength, Scriptpath, strRet

Dim WshShell: Set WshShell = WScript.CreateObject("WScript.Shell")
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim WshNetwork: Set WshNetwork = WScript.CreateObject("WScript.Network")
dBug = False

pathlength = Len(WScript.ScriptFullName) - Len(WScript.ScriptName)
Scriptpath = Mid(WScript.ScriptFullName, 1, pathlength)

Dim strDPassword: strDPassword = "TempPassword"
Dim strDUserName: strDUserName = "AdminAccount"

forceUseCScript

strComputerName = InputBox("Input Computer Name Here","This computer will be rebooted multiple times")

If Len(strComputerName) < 7 Then
	LogEntry "ERROR!!. Computer Name not correct. Check the name and try again. You entered " & strComputerName
	LogEntry "ERROR!!. The name you entered is only " & len(strComputerName) & " Characters long"
	WScript.Quit
End If


If EnableAccount(strComputerName) = False Then
	LogEntry "Error!! Not able to enable the computer account for " & strComputerName
	WScript.Quit(1)
End If
StrCompBOS = left(strComputerName,Len(strComputerName) - 5) & "RSVR01"
If Pingable(strComputerName) = False Then
	LogEntry "Error!! not able to ping " & strComputerName
	WScript.Quit(1)
End If
strPassword = GetPasswordFromBOS(StrCompBOS)
LogEntry "Password is: " & strPassword

If MapDrive(strComputerName,strPassword) = False Then
	LogEntry "Error!! not able to map drive to " & strComputerName
	WScript.Quit(1)
End If
If CopyFile(strComputerName,"Add") = False Then
	LogEntry "Error!! not able to copy Netdom to " & strComputerName
	WScript.Quit(1)
End If
If CreateBatFile(strComputerName,"Remove") = False Then
	LogEntry "Error!! not able to Create Removal bat file on " & strComputerName
	LogEntry "Error!! not able to Create Removal bat file on " & strComputerName
End If

If DoAction(strComputerName) = False Then
	LogEntry "Error!! not able to execute Psexec job for removal on " & strComputerName
	'WScript.Quit(1)
End If
If Reboot(strComputerName) = False Then
	LogEntry "Error!! " & strComputerName & " Did not reboot successfully"
	WScript.Quit(1)
End If
If MapDrive(strComputerName,strPassword) = False Then
	LogEntry "Error!! not able to map drive to add the computer " & strComputerName & " to the domain"
	WScript.Quit(1)
End If
WScript.Sleep 5000
If CreateBatFile(strComputerName,"Add") = False Then
	LogEntry "Error!! not able to Create addition bat file on " & strComputerName
	WScript.Quit(1)
End If
If DoAction(strComputerName) = False Then
	LogEntry "Error!! not able to execute Psexec job to add machine to domain"
	WScript.Quit(1)
End If
If CreateBatFile(strComputerName,"RemoveFile") = False Then
	LogEntry "Error!! not able to remove bat file on " & strComputerName
	WScript.Quit(1)
End If
If CopyFile(strComputerName,"Remove") = False Then
	LogEntry "Error!! not able to Remove Netdom From " & strComputerName
	WScript.Quit(1)
End If
strRet = WshShell.Run("net use z: /delete",,True)
If strRet = 0 Then
	LogEntry "Successfully deleted Drive Z"
Else
	LogEntry "Problem deleting Z: drive. Exiting with errorcode " & Err.Number
End If
If Reboot(strComputerName) = False Then
	LogEntry "Error!! " & strComputerName & " Did not reboot successfully on the second time"
	WScript.Quit(1)
End If

LogEntry "Successfully removed, re-added and verified the computer account was enabled for " & strComputerName & " To the domain. Now exiting program."
' 
Function EnableAccount(strComputerName)

	Dim strDN: strDN = GetDN(strComputerName)
	Dim strPath: strPath = "LDAP://" & strDN
	Dim objNamespaceLDAP, objMyObject
	
	Set objNamespaceLDAP = GetObject("LDAP:")
	Err.Clear
	Set objMyObject = objNamespaceLDAP.OpenDSObject(strPath,strDUserName,strDPassword,0)
	If Err <> 0 Then
		LogEntry "Error connecting to AD to enable Computer account."
		Exit Function
	End If
	Err.Clear
	objMyObject.AccountDisabled = False
	objMyObject.SetInfo 
	objMyObject = Null
	If Err <> 0 Then
		LogEntry "Error enabling the Computer account."
		Exit Function
	Else
		LogEntry "Verified the Computer account is enabled."
		EnableAccount = True
	End If
	
End Function

Function GetDN (strComputerName)
	
	Dim objTrans, objDomain
	
	Const ADS_NAME_INITTYPE_GC = 3
	Const ADS_NAME_TYPE_NT4 = 3
	Const ADS_NAME_TYPE_1779 = 1
	Set objTrans = CreateObject("NameTranslate")
	Set objDomain = getObject("LDAP://rootDse")
	objTrans.Init ADS_NAME_INITTYPE_GC, ""
	objTrans.Set ADS_NAME_TYPE_NT4, wshNetwork.UserDomain & "\" _
	& strComputerName & "$"
	GetDN = objTrans.Get(ADS_NAME_TYPE_1779)
	'Set DN to upper Case
	GetDN = UCase(GetDN)
	
End Function

Sub LogEntry (strInfo) 
	
	WScript.Echo Now() & ": " & strInfo
	
End Sub

Sub forceUseCScript()   

	If Not WScript.FullName = WScript.Path & "\cscript.exe" Then 
		WshShell.Run "cmd.exe /k " & WScript.Path & "\cscript.exe //NOLOGO " & Chr(34) & WScript.scriptFullName & Chr(34),1,False      
		WScript.Quit 0   
	End If
	
End Sub 

Function CopyFile(strComputerName,Action)
	
	Err.Clear
	CopyFile = False
	If Action = "Add" Then
		If objFSO.FileExists(Scriptpath & "netdom.exe") Then
			LogEntry Scriptpath & "netdom.exe" & "\\" & strComputerName & "\admin$\Netdom.exe"
			objFSO.CopyFile Scriptpath & "netdom.exe","\\" & strComputerName & "\admin$\"
			If Err.Number = 0 Then
				LogEntry "Successfully Copied Netdom to " & strComputerName
				CopyFile = True
			Else
				LogEntry "Error!! Copying Netdom to " & strComputerName
				Exit Function
			End If
		Else
			wscript.echo Scriptpath & "netdom.exe doesn't exist.. Exiting script."
			Exit Function
		End If
	Else
		If objFSO.FileExists("\\" & strComputerName & "\admin$\netdom.exe")  = True Then
			strRet = objFSO.DeleteFile("\\" & strComputerName & "\admin$\netdom.exe")
			If strRet = 0 Then
				LogEntry "Successfully deleted Netdom from " & strComputerName
				CopyFile = True
			Else
				LogEntry "Error!! deleting Netdom from " & strComputerName
				Exit Function
			End If
		Else
			LogEntry "Verified Netdom not on " & strComputerName
			CopyFile = True
		End If
	End If
		
End Function

Function CreateBatFile(strComputerName,role)

	Dim CommandLine
	Dim objTextFile
	Const ForAppending = 8

	CreateBatFile = False
	
	If role = "Add" Then
		CommandLine = "netdom.exe join " & strComputerName & " /d:MyDomain.com /userd:" & strDUserName &  " /Passwordd:" & strDPassword & " /Verbose"
	Else
		CommandLine = "netdom.exe remove " &  strComputerName & " /domain:MyDomain /userd:" & strDUserName & " /Passwordd:" & strDPassword
	End If
	strBatFile = "\\" & strComputerName & "\admin$\action.bat"
	Err.Clear
	If objFSO.FileExists(strBatFile) Then
		LogEntry "File " & strBatFile & " exists.. "
		objFSO.DeleteFile(strBatFile)
		If Err.Number <> 0 Then
			LogEntry "Error!! Can't delete " & strBatFile
			Exit Function
		Else
			LogEntry "Successfully deleted " & strBatFile
		End If
		If role = "RemoveFile" Then
			CreateBatFile = True
			Exit Function
		End If
	End If
	Err.Clear
	Set objTextFile = objFSO.OpenTextFile(strBatFile, ForAppending, True)
	If Err.Number <> 0 Then
		LogEntry "Error!! Can't write to " & strBatFile
		Exit Function
	Else
		CreateBatFile = True
		LogEntry "Successfully Created " & strBatFile
	End If
	objTextFile.WriteLine("@Echo ON")
	objTextFile.WriteLine(CommandLine)
	objTextFile.Close

End Function 

Function DoAction(strComputerName)

	DoAction = False
	Dim Status
	Dim strCommand
	Dim strCount: strCount = 0
	strCommand = "cmd /c psexec.exe \\" & strComputerName &  " action.bat"
	LogEntry strCommand
	
	
	Do While strCount <> 10
		Status = WshShell.Run(strCommand,,True)
		If Status = 0 Or Status = 2692 Then
			LogEntry "Successfully Ran the remote Bat file"
			DoAction = True
			Exit Function
		Else
			LogEntry "Problem Running the remote Bat file. Exiting with errorcode " & Status & " trying " & 3 - strCount & " More Times"
			WScript.Sleep (3000)
			strCount = strCount + 1
			If strCount > 3 Then
				Exit Function
			End If
		End If
		Err.Clear
	Loop

End Function

Function Mapdrive(strComputerName, strPassword)

	Mapdrive = False
	Dim strCommand
	
	strCommand = "net.exe use z: /delete"
	strRet = WshShell.Run(strCommand,,True)
	If strRet = 0 or strRet = 2 Then
		LogEntry "Successfully deleted Drive Z"
	Else
		LogEntry "Problem deleting Z: drive. Exiting with errorcode " & strRet
		LogEntry "Command: " & strCommand
		Exit Function
	End If
	Err.Clear
	
	strCommand = "net.exe use z: \\" & strComputerName & "\c$ " & _
		strPassword & " /u:" & strComputerName & "\administrator"
	strRet = WshShell.Run(strCommand,,True)
	If strRet = 0 Then
		LogEntry "Successfully Mapped Z Drive to " & "\\" & strComputerName & "\c$"
		Mapdrive = True
	Else
		LogEntry "Problem Mapping drive to \\" & strComputerName & "\c$ Exit code is: " & strRet
		LogEntry "Command Line: " & strCommand
		Exit Function
	End If

End Function

Function GetPasswordFromBOS(StrCompBOS)
	
	Dim strKeyPath, strValue, strValueName
	Dim oLocator, oService, oRegistry
	if dBug = False Then On Error Resume Next 
	
	Const HKEY_LOCAL_MACHINE = &H80000002
	Const REG_SZ = 1
	
	strKeyPath ="SYSTEM\MyDomain"
	strValueName="DefaultPasswordPOS" 
	
	Set oRegistry=GetObject("winmgmts:\\" & StrCompBOS & "\root\default:StdRegProv") 
	
	oRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue 
	
	If isnull(strValue) = true Then
		strValue = "password"
		LogEntry "Error getting password from " & StrCompBOS & " Setting to default: password"
	Else
		LogEntry "Password retrieved successfully. Password from BOS (" & StrCompBOS & " is: " & strValue
	End If
	
	If strValue = "" Then strValue = "password"
	
	GetPasswordFromBOS = strValue

End Function

Function Reboot(strComputerName)
	
	Reboot = False
	Dim intCount: intCount = 0
	
	Err.Clear
	strRet = WshShell.Run ("shutdown /r /f /t 0 /m \\" & strComputerName,True)
	If strRet = 0 Then
		LogEntry "Successfully sent reboot command for " & strComputerName
	Else
		LogEntry "Problem sending reboot command for " & strComputerName & " Exit code is: " & Err.code
		Exit Function
	End If
	Dim count: count = 0
	Do While Reboot = False
		
		Do Until Pingable(strComputerName) = False 
			count = count + 1
			WScript.Sleep(5000)
			If count > 50 Then
				LogEntry "Problem shutting down remote computer. I have tried for over 5 minutes"
				Exit Function
			End If
		Loop
		LogEntry "Machine has finally shutdown"

		count = 0
		Do Until Pingable(strComputerName) = True
			WScript.Sleep(5000)
			If count > 50 Then
				LogEntry "Computer not starting up. I have waited for over 5 minutes"
				Exit Function
			End If
		Loop
		
		LogEntry "Machine is now pingable"
		
		count = 0
		Do Until ConnectToClientViaWMI(strComputerName) = True
			WScript.Sleep(5000)
			If count > 50 Then
				LogEntry "Not able to connect to machine via WMI. I have waited for over 5 minutes"
				Exit Function
			End If
		Loop
		LogEntry "Successfully connected to WMI on " & strComputerName 
		
		Reboot = True
	Loop
	
End Function

Function Pingable(strComputer)
	Pingable = False
	Dim wmiQuery, objWMIService, objPing, objStatus
	
	wmiQuery = "Select * From Win32_PingStatus Where Address = '" & strComputer & "'"
	
	Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
	Set objPing = objWMIService.ExecQuery(wmiQuery)
	
	For Each objStatus in objPing
		If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
		Else
			Pingable = True 'if computer is reachable, return true
		End If
	Next
	
End Function

Function ConnectToClientViaWMI(strComputer)
	
	ConnectToClientViaWMI = False
	Dim wmiQuery, objWMIService, objPing, objStatus, objSWbemLocator
	
	On Error Resume Next

	Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
	Set objWMIService = objSWbemLocator.ConnectServer _
    	(strComputer, "root\cimv2", strComputer & "\administrator", strPassword)
	objWMIService.Security_.ImpersonationLevel = 3
		
	If Err.Number = 0 Then
		ConnectToClientViaWMI = True	
	End If

End Function

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:tomtom98
ID: 36529338
We add computer in AD first....Will this ask for username/password?
0
 

Author Comment

by:tomtom98
ID: 36529444
how do i set it up to run on the local machine..we go to the physical machine and then rename it at the machine?
0
 
LVL 7

Accepted Solution

by:
ednetman earned 500 total points
ID: 36562960
Running the script on a local machine, that is already on the domain, use this script.

(Limited testing as I haven't had a lot of time lately, but I'll mess with it in VMware tonight when I get home.)

Const JOIN_DOMAIN = 1
Const ACCT_CREATE = 2
Const ACCT_DELETE = 4
Const WIN9X_UPGRADE = 16C
onst DOMAIN_JOIN_IF_JOINED = 32
Const JOIN_UNSECURE = 64
Const MACHINE_PASSWORD_PASSED = 128
Const DEFERRED_SPN_SET = 256
Const INSTALL_INVOCATION = 262144
Dim message
Dim IP

strDomain = <DOMAIN NAME>
strUser = <UserName>
strPassword = <ADMIN PASSWORD>

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

Set objWMIService = GetObject ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")
Set colAdapters = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")

title = "Join computer to domain"
message = "Please enter computer name. Leave blank or press cancel to quit. & vbCrLf & vbCrLf & "Generated name: " & generatedName
newComputerName = InputBox(message, title)

If newComputerName = "" Then
    Wscript.quit
End If

areYousure = MsgBox("Are you sure you want t0 add computer to domain with name:" & vbCrLf & vbCrLf & newComputerName, vbYesNo + vbQuestion,"Add computer to domain")

If areYouSure = "7" Then
    MsgBox "Exiting script.",vbInformation
    Wscript.quit
End If

Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & _
    strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & _
        strComputer & "'") 

ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, strPassword, strDomain & "\" & strUser, "ou=My_Computer_OU,DC=mycorp,dc=com", _
        JOIN_DOMAIN + ACCT_CREATE)


If ReturnValue = 0 Then
    MsgBox "Computer added to domain under old name without error. proceeding to change computer name. "
Else
    MsgBox "Computer not added to domain successfully. Return value: " & ReturnValue
End If

strComputer = "."Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colComputers = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

For Each objComputer in colComputers
    MsgBox "About to rename computer to: " & newComputername
        ErrCode = objComputer.Rename(newComputerName, strPassword, strUser)
    If ErrCode = 0 Then
        MsgBox "Computer renamed correctly."
    Else
        MsgBox "Eror changing computer name. Error code: " & ErrCode    End If
Next

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

If you have done a reformat of your hard drive and proceeded to do a successful Windows XP installation, you may notice that a choice between two operating systems when you start up the machine. Here is how to get rid of this: Click Start Clic…
Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this i…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now