error when join xp to domain

Anything VBScript-related, including Windows Script Host, WMI, ADSI, and more.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 14 years and 8 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
funnysun
Posts: 15
Last visit: Thu Jul 09, 2009 4:17 am

error when join xp to domain

Post by funnysun »

Hey guys,

i'm having trouble with my vbs when join xp box back to domain.

what my code does is to search domain first for local xp workstation and delete existing computer account if it's in AD then join it to Ad again to the OU where it originally was.
There is no problem with removing existing account. but i always got return value 2 if i run vbs first time. if I run it second time, vbs tells me local computer is not in AD, then join it to AD with no problem.

the error happens only when join xp back to AD on the first time running this vbs, i did a little bit research, but couldnt find what return value 2 means.

Anyway, here is my HTA with vbs code, could someone please help?

Many thanks


<html><head><title>Add Computer To Domain</title><style type="text/css"><!--.style2 {font-family: Arial, Helvetica, sans-serif}.style3 {font-weight: bold}.style4 { font-weight: bold; font-size: 12px;}.style5 {font-weight: bold}.style6 {font-family: Arial, Helvetica, sans-serif; font-size: 10px;}.style7 { font-size: 14px}.style8 {font-size: 12px}--></style></head><HTA:APPLICATION APPLICATIONNAME="Add Computer To Domain" SCROLL="No" SINGLEINSTANCE="Yes" borderstyle="Thin" minimizebutton="No" maximizebutton="No" icon=""></head><body> <div align="left"> <table width="287" height="128" border="0"> <tr> <td colspan="2"><div align="center" class="style6 style7"><strong>Add Computer To Domain</strong></div></td> </tr> <tr> <td width="121"><div align="center" class="style2 style3"> <div align="right"><span class="style8">Computer Name</span>: </div> </div></td> <td width="150"><div align="center" class="style2"> <input type="text" maxlength="20" size="20" name="txt_computername"> </div></td> </tr> <tr> <td><div align="center" class="style5 style2 style4"> <div align="right">User Name:</div> </div></td> <td><div align="center" class="style2"> <input type="text" maxlength="30" size="20" name="txt_username"> </div></td> </tr> <tr> <td><div align="center" class="style2 style5"> <div align="right" class="style8">Password:</div> </div></td> <td><div align="center" class="style2"> <input type="password" maxlength="30" size="20" name="txt_password"> </div></td> </tr> <tr> <td colspan="2"><div align="center"><input id="cmdAdd" type="button" value="Add To Domain" onClick="vbs:Add2domain"> </div></td> </tr> </table></div></body><SCRIPT Language="VBScript">
Dim objFile,fname,strLogDir,strAdsPathDim strOU:strOU=""Dim strDomain:strDomain="test"Dim strDomainDN:strDomainDN="DC=test,DC=org"Dim strDN:strDN="test.org"Dim strDC:strDC="dc01"Dim msgSub Window_onload CenterWindow 350, 200 Set objNetwork = CreateObject("WScript.Network") txt_computername.Value = objNetwork.ComputerName End Sub Sub CenterWindow( widthX, heightY ) self.ResizeTo widthX, heightY self.MoveTo (screen.Width - widthX)/2, (screen.Height - heightY)/2 End Sub Sub Add2Domain Dim strUser:strUser=Trim(txt_username.Value)Dim strPassword:strPassword=Trim(txt_password.Value)Dim strComputer:strComputer=Trim(txt_computername.Value)Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 3Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2
If Trim(txt_username.Value) = "" Then MsgBox "Please enter a username." txt_username.Focus ElseIf Trim(txt_password.value) = "" Then MsgBox "Please enter a password." txt_password.Focus ElseIf IsConnectible=False Then MsgBox "Not able to contact Domain Controller, please check network connection !" Exit Sub Else
On Error Resume Next
Set WshShell =CreateObject("Wscript.Shell")Set objFSO = CreateObject("Scripting.FileSystemObject")WshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 0, "REG_DWORD" strLogDir="C:"If objFSO.FileExists(strLogDir & "JoinDomainLog.txt") Then Set objFile = objFso.OpenTextFile(strLogDir & "JoinDomainLog.txt",ForWriting) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU=""Else fname=strLogDir & "JoinDomainLog.txt" Set objFile = objFso.CreateTextFile (fname, True) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU=""
End IfWshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 1, "REG_DWORD" End IfEnd Sub
Function ShutDown(strComputer)
msg=MsgBox("Do you want to restart ?",vbYesNo,"")If msg=vbNo ThenExit FunctionElse Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2:Win32_Process")E = objWMIService.Create("cmd /c shutdown -r -t 30 ", null, null, intProcessID)
Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!" & strComputer & "rootcimv2") Set OperatingSystems = WMIService.ExecQuery("Select * From Win32_OperatingSystem") For Each OperatingSystem in OperatingSystems OperatingSystem.Reboot() Nextif E = 0 Then ShutDown = "OK"end IfobjFile.Writeline "Computer Booted :" & NowEnd IfEnd Function
Function Join2Domain(strComputer,strDomain,strUser,strPassword,strOU)Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2Const JOIN_DOMAIN = 1Const ACCT_CREATE = 2
msg = MsgBox ("Join """&strComputer&""" to domain ?",vbYesNo,"")If msg=vbNo Thenmsg=""Exit FunctionElseSet objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!" & _ strComputer & "rootcimv2:Win32_ComputerSystem.Name='" & _ strComputer & "'") msgbox strOU ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain,strPassword,strUser,strOU,JOIN_DOMAIN+ACCT_CREATE)
If ReturnValue=0 ThenobjFile.WriteLine "Successfully joined """&strComputer&""" to domain """&strDomain&""""MsgBox "Successfully joined """&strComputer&""" to domain """&strDomain&""" with ReturnValue """&ReturnValue&""""Else objFile.WriteLine "This computer """&strComputer&""" failed to join domain """&strDomain&""" Return value is """&ReturnValue&"""" MsgBox "Failed to join """&strComputer&""" to domain """&strDomain&""" Return value is """&ReturnValue&"""" End If 'strOU=""End If End Function
Function HTASleep(intSeconds) Dim objShell, strCommand Set objShell = CreateObject("Wscript.Shell") cmdAdd.Disabled=TruestrCommand = "%COMSPEC% /c ping -n " & 1 + intSeconds & " 127.0.0.1>nul" objShell.Run strCommand, 0, True Set objShell = Nothing cmdAdd.Disabled=FalseEnd Function
Function IsConnectible()
Set objShell = CreateObject("WScript.Shell")Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strDN)strPingResults = LCase(objExec.StdOut.ReadAll)If InStr(strPingResults, "reply from") Then IsConnectible=TrueElse IsConnectible=FalseEnd IfEnd Function
Function DelAcct(strComputer,strDomain,strUser,strPassword)Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 1Set objConnection = CreateObject("ADODB.Connection")Set objCommand = CreateObject("ADODB.Command")objConnection.Provider = "ADsDSOObject"objConnection.Properties("User ID") = strUserobjConnection.Properties("Password") = strPasswordobjConnection.Properties("Encrypt Password") = TrueobjConnection.Properties("ADSI Flag") = 1 objConnection.Open "Active Directory Provider"Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 100objCommand.Properties("Cache Results") = FalseobjCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = _ "SELECT ADsPath FROM 'LDAP://" & strDomain & "' WHERE objectCategory='computer' " & _ "AND Name='" & strComputer & "'"Set objRecordSet = objCommand.ExecuteIf objRecordSet.EOF ThenMsgBox "This Computer """&strComputer&""" is not in domain """&strDomain&""""objFile.WriteLine "This Computer """&strComputer&""" is not in domain """&strDomain&""""Else msg=MsgBox ("Remove """&strComputer&""" from domain """&strDomain&"""?",vbYesNo,"") If msg =vbNo Then msg="" Else objRecordSet.MoveFirst strADsPath = "" While Not objRecordSet.EOF strAdsPath = objRecordSet.Fields("ADsPath").Value intDNLength = Len(strAdsPath)- Len("LDAP://"&strDomain&"/CN=")-Len (strComputer)-Len (",") strOU=Right(strAdsPath, intDNLength) objRecordSet.MoveNext Wend Set objNS = GetObject("LDAP:") Set objComputer = objNS.OpenDSObject(strADsPath, strUser, strPassword, ADS_SECURE_AUTHENTICATION) objComputer.DeleteObject (0) 'objFile.WriteLine "Computer path: " & strOU MsgBox "This computer"""&strComputer&""" was removed from domain """&strDomain&"""" objFile.WriteLine "This computer"""&strComputer&""" was removed from AD " End If End If End Function
</Script></html>
User avatar
funnysun
Posts: 15
Last visit: Thu Jul 09, 2009 4:17 am

error when join xp to domain

Post by funnysun »

Hey guys,

i'm having trouble with my vbs when join xp box back to domain.

what my code does is to search domain first for local xp workstation and delete existing computer account if it's in AD then join it to Ad again to the OU where it originally was.
There is no problem with removing existing account. but i always got return value 2 if i run vbs first time. if I run it second time, vbs tells me local computer is not in AD, then join it to AD with no problem.

the error happens only when join xp back to AD on the first time running this vbs, i did a little bit research, but couldnt find what return value 2 means.

Anyway, here is my HTA with vbs code, could someone please help?

Many thanks


<html><head><title>Add Computer To Domain</title><style type="text/css"><!--.style2 {font-family: Arial, Helvetica, sans-serif}.style3 {font-weight: bold}.style4 { font-weight: bold; font-size: 12px;}.style5 {font-weight: bold}.style6 {font-family: Arial, Helvetica, sans-serif; font-size: 10px;}.style7 { font-size: 14px}.style8 {font-size: 12px}--></style></head><HTA:APPLICATION APPLICATIONNAME="Add Computer To Domain" SCROLL="No" SINGLEINSTANCE="Yes" borderstyle="Thin" minimizebutton="No" maximizebutton="No" icon=""></head><body> <div align="left"> <table width="287" height="128" border="0"> <tr> <td colspan="2"><div align="center" class="style6 style7"><strong>Add Computer To Domain</strong></div></td> </tr> <tr> <td width="121"><div align="center" class="style2 style3"> <div align="right"><span class="style8">Computer Name</span>: </div> </div></td> <td width="150"><div align="center" class="style2"> <input type="text" maxlength="20" size="20" name="txt_computername"> </div></td> </tr> <tr> <td><div align="center" class="style5 style2 style4"> <div align="right">User Name:</div> </div></td> <td><div align="center" class="style2"> <input type="text" maxlength="30" size="20" name="txt_username"> </div></td> </tr> <tr> <td><div align="center" class="style2 style5"> <div align="right" class="style8">Password:</div> </div></td> <td><div align="center" class="style2"> <input type="password" maxlength="30" size="20" name="txt_password"> </div></td> </tr> <tr> <td colspan="2"><div align="center"><input id="cmdAdd" type="button" value="Add To Domain" onClick="vbs:Add2domain"> </div></td> </tr> </table></div></body><SCRIPT Language="VBScript">
Dim objFile,fname,strLogDir,strAdsPathDim strOU:strOU=""Dim strDomain:strDomain="test"Dim strDomainDN:strDomainDN="DC=test,DC=org"Dim strDN:strDN="test.org"Dim strDC:strDC="dc01"Dim msgSub Window_onload CenterWindow 350, 200 Set objNetwork = CreateObject("WScript.Network") txt_computername.Value = objNetwork.ComputerName End Sub Sub CenterWindow( widthX, heightY ) self.ResizeTo widthX, heightY self.MoveTo (screen.Width - widthX)/2, (screen.Height - heightY)/2 End Sub Sub Add2Domain Dim strUser:strUser=Trim(txt_username.Value)Dim strPassword:strPassword=Trim(txt_password.Value)Dim strComputer:strComputer=Trim(txt_computername.Value)Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 3Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2
If Trim(txt_username.Value) = "" Then MsgBox "Please enter a username." txt_username.Focus ElseIf Trim(txt_password.value) = "" Then MsgBox "Please enter a password." txt_password.Focus ElseIf IsConnectible=False Then MsgBox "Not able to contact Domain Controller, please check network connection !" Exit Sub Else
On Error Resume Next
Set WshShell =CreateObject("Wscript.Shell")Set objFSO = CreateObject("Scripting.FileSystemObject")WshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 0, "REG_DWORD" strLogDir="C:"If objFSO.FileExists(strLogDir & "JoinDomainLog.txt") Then Set objFile = objFso.OpenTextFile(strLogDir & "JoinDomainLog.txt",ForWriting) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU=""Else fname=strLogDir & "JoinDomainLog.txt" Set objFile = objFso.CreateTextFile (fname, True) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU=""
End IfWshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 1, "REG_DWORD" End IfEnd Sub
Function ShutDown(strComputer)
msg=MsgBox("Do you want to restart ?",vbYesNo,"")If msg=vbNo ThenExit FunctionElse Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2:Win32_Process")E = objWMIService.Create("cmd /c shutdown -r -t 30 ", null, null, intProcessID)
Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!" & strComputer & "rootcimv2") Set OperatingSystems = WMIService.ExecQuery("Select * From Win32_OperatingSystem") For Each OperatingSystem in OperatingSystems OperatingSystem.Reboot() Nextif E = 0 Then ShutDown = "OK"end IfobjFile.Writeline "Computer Booted :" & NowEnd IfEnd Function
Function Join2Domain(strComputer,strDomain,strUser,strPassword,strOU)Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2Const JOIN_DOMAIN = 1Const ACCT_CREATE = 2
msg = MsgBox ("Join """&strComputer&""" to domain ?",vbYesNo,"")If msg=vbNo Thenmsg=""Exit FunctionElseSet objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!" & _ strComputer & "rootcimv2:Win32_ComputerSystem.Name='" & _ strComputer & "'") msgbox strOU ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain,strPassword,strUser,strOU,JOIN_DOMAIN+ACCT_CREATE)
If ReturnValue=0 ThenobjFile.WriteLine "Successfully joined """&strComputer&""" to domain """&strDomain&""""MsgBox "Successfully joined """&strComputer&""" to domain """&strDomain&""" with ReturnValue """&ReturnValue&""""Else objFile.WriteLine "This computer """&strComputer&""" failed to join domain """&strDomain&""" Return value is """&ReturnValue&"""" MsgBox "Failed to join """&strComputer&""" to domain """&strDomain&""" Return value is """&ReturnValue&"""" End If 'strOU=""End If End Function
Function HTASleep(intSeconds) Dim objShell, strCommand Set objShell = CreateObject("Wscript.Shell") cmdAdd.Disabled=TruestrCommand = "%COMSPEC% /c ping -n " & 1 + intSeconds & " 127.0.0.1>nul" objShell.Run strCommand, 0, True Set objShell = Nothing cmdAdd.Disabled=FalseEnd Function
Function IsConnectible()
Set objShell = CreateObject("WScript.Shell")Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strDN)strPingResults = LCase(objExec.StdOut.ReadAll)If InStr(strPingResults, "reply from") Then IsConnectible=TrueElse IsConnectible=FalseEnd IfEnd Function
Function DelAcct(strComputer,strDomain,strUser,strPassword)Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 1Set objConnection = CreateObject("ADODB.Connection")Set objCommand = CreateObject("ADODB.Command")objConnection.Provider = "ADsDSOObject"objConnection.Properties("User ID") = strUserobjConnection.Properties("Password") = strPasswordobjConnection.Properties("Encrypt Password") = TrueobjConnection.Properties("ADSI Flag") = 1 objConnection.Open "Active Directory Provider"Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 100objCommand.Properties("Cache Results") = FalseobjCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = _ "SELECT ADsPath FROM 'LDAP://" & strDomain & "' WHERE objectCategory='computer' " & _ "AND Name='" & strComputer & "'"Set objRecordSet = objCommand.ExecuteIf objRecordSet.EOF ThenMsgBox "This Computer """&strComputer&""" is not in domain """&strDomain&""""objFile.WriteLine "This Computer """&strComputer&""" is not in domain """&strDomain&""""Else msg=MsgBox ("Remove """&strComputer&""" from domain """&strDomain&"""?",vbYesNo,"") If msg =vbNo Then msg="" Else objRecordSet.MoveFirst strADsPath = "" While Not objRecordSet.EOF strAdsPath = objRecordSet.Fields("ADsPath").Value intDNLength = Len(strAdsPath)- Len("LDAP://"&strDomain&"/CN=")-Len (strComputer)-Len (",") strOU=Right(strAdsPath, intDNLength) objRecordSet.MoveNext Wend Set objNS = GetObject("LDAP:") Set objComputer = objNS.OpenDSObject(strADsPath, strUser, strPassword, ADS_SECURE_AUTHENTICATION) objComputer.DeleteObject (0) 'objFile.WriteLine "Computer path: " & strOU MsgBox "This computer"""&strComputer&""" was removed from domain """&strDomain&"""" objFile.WriteLine "This computer"""&strComputer&""" was removed from AD " End If End If End Function
</Script></html>
User avatar
funnysun
Posts: 15
Last visit: Thu Jul 09, 2009 4:17 am

error when join xp to domain

Post by funnysun »

my appologies, i'm still new to vbs, really sorry about that :(i have modified my vbs again as following, let me know if this is ok.btw, each function is tested work as standalone vbs.On Error Resume NextSub Add2Domain Dim objFile,fname,strLogDir,strAdsPathDim strOU:strOU=""Dim strDomain:strDomain="test"Dim strDomainDN:strDomainDN="DC=test,DC=org"Dim strDN:strDN="test.org"Dim strDC:strDC="dc01"Dim msgDim strComputerDim strPassword="password"Dim strUser="user1"Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 3Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2Set objNetwork = CreateObject("WScript.Network") strComputer = objNetwork.ComputerNameIf IsConnectible=False Then MsgBox "Not able to contact Domain Controller, please check network connection !" Exit SubElse Set WshShell =CreateObject("Wscript.Shell") Set objFSO = CreateObject("Scripting.FileSystemObject") WshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 0, "REG_DWORD" strLogDir="C:" If objFSO.FileExists(strLogDir & "JoinDomainLog.txt") Then Set objFile = objFso.OpenTextFile(strLogDir & "JoinDomainLog.txt",ForWriting) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU="" Else fname=strLogDir & "JoinDomainLog.txt" Set objFile = objFso.CreateTextFile (fname, True) objFile.WriteLine "Log Started : " & Now objFile.WriteLine DelAcct strComputer,strDN,strDomain&""&strUser,strPassword objFile.WriteLine HTASleep(10) Join2Domain strComputer,strDomain,strDomain&""&strUser,strPassword,strOU objFile.WriteLine ShutDown strComputer objFile.close strOU="" End If WshShell.RegWrite "HKCUSoftwareMicrosoftWindowsCurrentVersionInternet SettingsZones11406", 1, "REG_DWORD"End IfEnd Sub'this function reboots computerFunction ShutDown(strComputer) msg=MsgBox("Do you want to restart ?",vbYesNo,"") If msg=vbNo Then Exit Function Else Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2:Win32_Process") E = objWMIService.Create("cmd /c shutdown -r -t 30 ", null, null, intProcessID) Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!" & strComputer & "rootcimv2") Set OperatingSystems = WMIService.ExecQuery("Select * From Win32_OperatingSystem") For Each OperatingSystem in OperatingSystems OperatingSystem.Reboot() Next if E = 0 Then ShutDown = "OK" end If objFile.Writeline "Computer Booted :" & Now End IfEnd Function'Join current computer to domainFunction Join2Domain(strComputer,strDomain,strUser,strPassword,strOU)Const HKEY_LOCAL_MACHINE = &H80000002Const ForReading = 1Const ForWriting = 2Const JOIN_DOMAIN = 1Const ACCT_CREATE = 2 msg = MsgBox ("Join """&strComputer&""" to domain ?",vbYesNo,"") If msg=vbNo Then msg="" Exit Function Else Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!" & _ strComputer & "rootcimv2:Win32_ComputerSystem.Name='" & _ strComputer & "'") msgbox strOU ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain,strPassword,strUser,strOU,JOIN_DOMAIN+ACCT_CREATE) If ReturnValue=0 Then objFile.WriteLine "Successfully joined """&strComputer&""" to domain """&strDomain&"""" MsgBox "Successfully joined """&strComputer&""" to domain """&strDomain&""" with ReturnValue """&ReturnValue&"""" Else objFile.WriteLine "This computer """&strComputer&""" failed to join domain """&strDomain&""" Return value is """&ReturnValue&"""" MsgBox "Failed to join """&strComputer&""" to domain """&strDomain&""" Return value is """&ReturnValue&"""" End If End If End Function'sleep function Function HTASleep(intSeconds) Dim objShell, strCommand Set objShell = CreateObject("Wscript.Shell") cmdAdd.Disabled=True strCommand = "%COMSPEC% /c ping -n " & 1 + intSeconds & " 127.0.0.1>nul" objShell.Run strCommand, 0, True Set objShell = Nothing cmdAdd.Disabled=FalseEnd Function'function to test connection to domain controllerFunction IsConnectible() Set objShell = CreateObject("WScript.Shell") Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strDN) strPingResults = LCase(objExec.StdOut.ReadAll) If InStr(strPingResults, "reply from") Then IsConnectible=True Else IsConnectible=False End IfEnd Function 'Search and delete existing computer account from AD 'if current computer name is already in domain.Function DelAcct(strComputer,strDomain,strUser,strPassword)Const ADS_SCOPE_SUBTREE = 2Const ADS_SECURE_AUTHENTICATION = 1 Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Properties("User ID") = strUser objConnection.Properties("Password") = strPassword objConnection.Properties("Encrypt Password") = True objConnection.Properties("ADSI Flag") = 1 objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 100 objCommand.Properties("Cache Results") = False objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = _ "SELECT ADsPath FROM 'LDAP://" & strDomain & "' WHERE objectCategory='computer' " & _ "AND Name='" & strComputer & "'" Set objRecordSet = objCommand.Execute If objRecordSet.EOF Then MsgBox "This Computer """&strComputer&""" is not in domain """&strDomain&"""" objFile.WriteLine "This Computer """&strComputer&""" is not in domain """&strDomain&"""" Else msg=MsgBox ("Remove """&strComputer&""" from domain """&strDomain&"""?",vbYesNo,"") If msg =vbNo Then msg="" Else objRecordSet.MoveFirst strADsPath = "" While Not objRecordSet.EOF strAdsPath = objRecordSet.Fields("ADsPath").Value intDNLength = Len(strAdsPath)- Len("LDAP://"&strDomain&"/CN=")-Len (strComputer)-Len (",") strOU=Right(strAdsPath, intDNLength) objRecordSet.MoveNext Wend Set objNS = GetObject("LDAP:") Set objComputer = objNS.OpenDSObject(strADsPath, strUser, strPassword, ADS_SECURE_AUTHENTICATION) objComputer.DeleteObject (0) MsgBox "This computer"""&strComputer&""" was removed from domain """&strDomain&"""" objFile.WriteLine "This computer"""&strComputer&""" was removed from AD " End If End IfEn
d Function
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

error when join xp to domain

Post by jvierra »

Here is a starter fix for your main loop.

Code: Select all

	
Function Add2Domain( sComputer, sDomain, sUser, sPassword, strOU )
	
    
    If IsConnectible( sComputer ) Then
        If DelAcct( sComputer, strDN, sDomain & "" & sUser,sPassword ) Then
            If Join2Domain( sComputer, sDomain, sDomain & "" & sUser, sPassword, strOU ) Then
                ShutDown sComputer 
             End If
       End If
    End If
    
End Function
	

After it works you can replace the MsgBox with a call to logging function.

Each of teh sub functions need to be designed to return true or false.

The function has NO code from the HTA so it can be run from VBS and moved t HTA WITHOUT changing any of the code.


Your code originally had On Error which was hiding a multitude of sins.

Start with this top level function and everything else will slowly fall into place. In the end you willsee how to execute a "structured" design.


jvierra2009-07-08 09:40:58
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

error when join xp to domain

Post by jvierra »

Here is your test function. Every other function will have this same pattern.

Code: Select all

	
Function IsConnectible( sComputer )
    Set wmi = GetObject("winmgmts://./root/CimV2")
    Set ping = wmi.ExecQuery("select * from Win32_PingStatus where address='" & sComputer & "'")
    For Each p In ping
        If p.StatusCode = 0 Then
            IsConnectible = True
            WriteLog "Ping successful to " & sComputer
        Else
            WriteLog "Ping failed to " & sComputer
        End If
    Next
End Function  
	
User avatar
funnysun
Posts: 15
Last visit: Thu Jul 09, 2009 4:17 am

error when join xp to domain

Post by funnysun »

so much appreciate your help
i will retest each of function again and get back to you
This topic is 14 years and 8 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked