Find Which OU A User Belongs To

email me

Find which OU a user belongs to

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

Set objUser = CreateObject("Wscript.Network")
FindUser = objUser.UserName 'InputBox("Please Enter A UserName", "Find User OU")
If FindUser = "" Then
MsgBox("No UserName Was Added")
WScript.Quit
Else
strUser = FindUser
End If

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
"SELECT distinguishedName FROM 'LDAP://dc=yourdomain,dc=com'WHERE objectCategory='user'AND sAMAccountName='" & strUser & "'"
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strDN = objRecordSet.Fields("distinguishedName").Value
arrPath = Split(strDN, ",")
intLength = Len(arrPath(1))
intNameLength = intLength - 3
Wscript.Echo "User :" & strUser & vbcrlf & "OU is : " & Right(arrPath(1), intNameLength)
objRecordSet.MoveNext
Loop