This script can be used to move an AD object (User, Group, computer etc) to a different OU within Active Directory.
Option Explicit
' Move-object.vbs ObjectToMove TargetOU ObjectType
'
' Move an AD object into a specific OU
' Search AD (from the root) to find the current location of the object.
On Error Resume Next
Dim strObject,strTargetOU,objTargetOU,objRootDSE,strDNSDomain,strTarget,objConnection,objCmd,objRecordSet
Dim Object,strParent,objParentOU,strObjectName,strObjectDN,strObjectOU
strObject = Wscript.Arguments(0)
strTargetOU = Wscript.Arguments(1)
strObjectType = Wscript.Arguments(2)
wscript.Echo "Move the Object " & strObject
'wscript.Echo & "into the OU: " & strTargetOU
Set objTargetOU = GetObject("LDAP://" & strTargetOU)
' Connect to the LDAP server's root object
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strTarget = "LDAP://" & strDNSDomain
' Connect to AD Provider
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
' Search command
Set objCmd = CreateObject("ADODB.Command")
Set objCmd.ActiveConnection = objConnection
' Query to match Object name
objCmd.CommandText = "SELECT Name, ADsPath,distinguishedName FROM '" & strTarget & "' WHERE objectCategory = strObjectType AND name='" & strObject & "'"
' Run the Search command
Const ADS_SCOPE_SUBTREE = 2
objCmd.Properties("Page Size") = 100
objCmd.Properties("Timeout") = 30
objCmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCmd.Properties("Cache Results") = False
Set objRecordSet = objCmd.Execute
' Iterate through the results
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strObjectName = objRecordSet.Fields("Name")
wscript.Echo "Object Name: " & strObjectName
strObjectDN = objRecordSet.Fields("distinguishedName")
wscript.Echo "Object DN: " & strObjectDN
objRecordSet.MoveNext
Loop
' Having the current OU we can bind directly to the Object that will be moved.
Set Object = GetObject("LDAP://" & strObjectDN)
wscript.Echo Object.ADsPath
' Optionally you may want to display the parent OU.
strParent = Object.Parent
'wscript.Echo "Parent: " & strParent
Set objParentOU = GetObject(strParent)
strObjectOU = objParentOU.distinguishedName
'wscript.Echo "ParentOU: " & strObjectOU
' Move the Object
On Error Resume Next
wscript.Echo "Move the Object [" & strObject & "] to " & strTargetOU
objTargetOU.MoveHere Object.ADsPath, vbNullString
if err.number <> 0 then
wscript.Echo "Error - failed."
else
wscript.Echo "Complete."
end if
On Error Goto 0
The valid AD Object types are: User, Contact, Group, Shared Folder, Printer, Computer, Domain Controllers, OU
Example
cscript Move-object.vbs "johndoe" "LDAP://OU=Users,DC=ss64,DC=com" "User"
“The majority of men meet with failure because of their lack of persistence in creating new plans to take the place of those which fail” ~ Napoleon Hill
Related:
SearchAD - Search AD for Users, Computers or groups