AD: Quickly Determine OU of User using VBScript
I'm working on a few Active Directory scripts that require knowing the full path or "distinguished name" of the user object. All I know initially is the username and domain name and I found a script at Hey, Scripting Guy! that is really useful -- it searches AD for the user's OU information. The only problem I had with the script is that it was properly done and thus, really long. At 26 lines, give or take, it cluttered my code so I decided to cut it down drastically. It's likely that my code isn't efficient and will probably take down the server one day but whatever, it sure is teeny!
1Const ADS_SCOPE_SUBTREE = 2
2
3Set objConnection = CreateObject("ADODB.Connection")
4Set objCommand = CreateObject("ADODB.Command")
5
6objConnection.Provider = "ADsDSOObject"
7objConnection.Open "Active Directory Provider"
8Set objCommand.ActiveConnection = objConnection
9
10objCommand.Properties("Page Size") = 1000
11objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
12
13objCommand.CommandText = _
14 "SELECT distinguishedName FROM 'LDAP://dc=fabrikam,dc=com' " & _
15 "WHERE objectCategory='user' " & _
16 "AND sAMAccountName='kenmyer'"
17
18Set objRecordSet = objCommand.Execute
19
20objRecordSet.MoveFirst
21Do Until objRecordSet.EOF
22 strDN = objRecordSet.Fields("distinguishedName").Value
23 arrPath = Split(strDN, ",")
24 intLength = Len(arrPath(1))
25 intNameLength = intLength - 3
26 Wscript.Echo Right(arrPath(1), intNameLength) ' outputs the OU name
27 objRecordSet.MoveNext
28Loop
Even shorter using a plain ADODB recordset to grab the distinguished name:
1Set rs = CreateObject("adodb.recordset")
2Connstring = "Provider=ADsDSOObject"
3strSQL = "SELECT distinguishedName FROM 'LDAP://dc=fabrikam,dc=com' " & _
4 "WHERE objectCategory='user' AND sAMAccountName='kenmyer'"
5
6rs.Open strSQL, Connstring
7If Not rs.EOF And Not rs.BOF Then
8 fullPath = rs("distinguishedName")
9End If
10
11rs.Close
12Set rs = Nothing