Return OU Path for Specific Computer

email me

Have you ever needed to know the exact path of a computer object? This script returns the full AD path for a specific computer.

 

Option Explicit

Dim oRoot, sDomain, strCommand
Dim sAdsPath, message
Dim strComputerName, retval
Dim WshShell

‘Get the ADsPath for the current domain to search.
Set oRoot = GetObject(“LDAP://rootDSE”)
sDomain = ORoot.Get(“defaultNamingContext”)

Set wshShell = WScript.CreateObject(“WScript.Shell”)
strComputerName = wshShell.ExpandEnvironmentStrings(“%ComputerNAME%”)

message = “This script will return the OU for a computer object.” & VbCrLf & _
VbCrLf & “The GC is searched, so you may start at the top. Search beginning in what domain?”
sDomain = InputBox(message,”Domain to Search”,sDomain)
If sDomain = “” Then WScript.Quit

message = “What is the computers:”
strComputerName = InputBox(message,”Computer Name”,strComputerName)

If strComputerName = “” Then WScript.Quit
strComputerName = UCase(strComputerName)

‘You can use LDAP:// instead

strCommand = “SELECT ADsPath FROM ‘GC://” & sDomain &”‘ WHERE objectCategory=’Computer’ ” & _
“AND Name ='” & strComputerName & “‘”
‘Get OU
sADSPath = ComputerOU()
‘bail if not found
If InStr(sAdsPath,”Not Found”) > 0 Then
retval = MsgBox (sADSPath,vbExclamation,”Search Failed” )
WScript.Quit
End If

‘else display results
retval = MsgBox(strComputerName & ” was found in this OU: ” & sADSPath & VbCrLf & VbCrLf &_
“Send OU Name to the clipboard?”,vbYesNo+vbInformation+vbDefaultButton2,”OU Name”)

If retval = vbYes Then ‘Use IE for clipboard
Dim objIE
Set objIE = CreateObject(“InternetExplorer.Application”)
objIE.Navigate(“about:blank”)
‘Note : intead of CRLF to save space
Do Until objIE.ReadyState=4: WScript.Sleep 1: Loop
objIE.Document.ParentWindow.ClipboardData.SetData “Text”, sADSPath
objIE.Quit
End If

‘ ======== Functions and Subs ==========
Function ComputerOU()
Dim oRS, ComputerPath, oADTmp
Dim oConn, oCommand
Const ADS_SCOPE_SUBTREE = 2
Set oConn = CreateObject(“ADODB.Connection”)
Set oCommand = CreateObject(“ADODB.Command”)
oConn.Provider = “ADsDSOObject”
oConn.Open “Active Directory Provider”
Set oCommand.ActiveConnection = oConn
‘Subtree required
oCommand.Properties(“Searchscope”) = ADS_SCOPE_SUBTREE
oCommand.CommandText = strCommand

Set oRS = oCommand.Execute

If oRS.BOF And oRS.EOF Then
ComputerOU = strComputerName & ” Not Found in ” & sDomain
Exit Function
End If

‘note unique answer means no need to loop
ComputerPath = oRS.Fields(“ADsPath”).Value
set oADTmp = GetObject(ComputerPath)
ComputerOU = mid(oADTmp.Parent,6)
End Function