VBScript to Return OU where User account is located

supportemea
supportemea used Ask the Experts™
on
Hey Guys,

Im trying to create a generic login script for a domain that has about 5 OU's of where users are located.

Im having a hard time finding a script that will return the OU of where a user account is located
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
This will give the OU location when user account is given
================================================

On Error Resume Next

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
FindUser = InputBox("Please Enter the 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 ADsPath FROM 'LDAP://dc="giveurdchere",dc="yourdc",dc="yourdc"'WHERE objectCategory='user'AND sAMAccountName='" & strUser & "'"
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("ADsPath").Value
    objRecordSet.MoveNext
Loop
===================================================
Most Valuable Expert 2012
Top Expert 2014

Commented:
Hi there, for a logon script, this will give you the breakdown of the path for your current user account, so you can pick which element you are after and change the index in
strOU = arrOU(1)

to suit.

Regards,

Rob.
Set objADSysInfo = CreateObject("ADSystemInfo")
arrOU = Split(objADSysInfo.UserName, ",")
strPath = "OU Path"
For intBit = LBound(arrOU) To UBound(arrOU)
	strPath = strPath & VbCrLf & "Element " & intBit & ": " & arrOU(intBit)
Next
MsgBox strPath
strOU = arrOU(1)
MsgBox strOU

Open in new window

Here is a simple script that returns the parent OU of the user account.

set objSysInfo = CreateObject("ADSystemInfo")
set objParent = GetObject("LDAP://" & objSysInfo.UserName)
wscript.echo "Parent OU = : " & objParent.parent

set objSysInfo = Nothing
set objParent = Nothing

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial