Recently I noticed that during the “Join Domain” step of my task sequence, that if the computer account already exists in AD somewhere other than the OU I want it added to, that the machine would successfully join the domain however it stays in whatever OU it was already in rather than move to the OU I specified. After searching around and finding no solution to this, I determined that I would need to put together a script to either delete the old computer account from AD prior to adding the imaging computer to AD, or to move the computer account to the correct OU after the “Join Domain” step. I ended up going after the second option of moving the computer account due to the fact that if you delete the old computer account, you loose any group memberships the old computer account might have been a member of.
So after a good 5 days of messing around with vbscript, I’ve got the following script. It can also be downloaded in a zip here.
Dim strComputer, objNetwork, strNameSet objNetwork = WScript.CreateObject(“WScript.Network”)strName = objNetwork.ComputerNameWScript.Echo “Computer Name: ” & strNameOn Error Resume NextConst ADS_SCOPE_SUBTREE = 2Set objConnection = CreateObject(“ADODB.Connection”)Set objCommand = CreateObject(“ADODB.Command”)objConnection.Provider = “ADsDSOObject”objConnection.Open “Active Directory Provider”Set objCommand.ActiveConnection = objConnectionobjCommand.Properties(“Page Size”) = 1000objCommand.Properties(“Searchscope”) = ADS_SCOPE_SUBTREEobjCommand.CommandText = _“SELECT ADsPath FROM ‘LDAP://dc=domain,dc=com’ WHERE objectCategory=’computer’ ” & _“AND name='” & strName & “‘”Set objRecordSet = objCommand.ExecuteobjRecordSet.MoveFirstDo Until objRecordSet.EOFstrADsPath = objRecordSet.Fields(“ADsPath”).ValueSet objOU = GetObject(“LDAP://OU=special ou,DC=domain,DC=com”)intReturn = objOU.MoveHere(strADsPath, vbNullString)objRecordSet.MoveNextLoop