AD: Quickly Determine OU of User using VBScript

Filed under: Active Directory, Quick Code, VBScript — Written by Chrissy on Thursday, November 16th, 2006 @ 7:39 pm

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!

Original Code

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
 
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
 
objCommand.CommandText = _
    "SELECT distinguishedName FROM 'LDAP://dc=fabrikam,dc=com' “ & _
        "WHERE objectCategory='user' " & _
            "AND sAMAccountName='kenmyer'"
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 Right(arrPath(1), intNameLength)
    objRecordSet.MoveNext
Loop

Shortened down to 7 lines and 1 object

  Set rs = CreateObject("adodb.recordset")
    Connstring = "Provider=ADsDSOObject"
    strSQL = "SELECT distinguishedName FROM 'LDAP://dc=fabrikam,dc=com' WHERE objectCategory='user' AND sAMAccountName='kenmyer'"
    rs.Open strSQL, Connstring
      if not rs.eof and not rs.bof Then fullPath = rs("distinguishedName")
    rs.close
  Set rs = Nothing
1 Comment   -
  • Comment by El Puño | February 12, 2008 @ 5:55 am

    This is faster routine I use :

    1 - Get the Adspath of the user and put it in UserAdsPath

    ResultArray = Split(Replace(UserAdsPath, "LDAP://", ""), ",")

    ResultArray(0) is the CN name
    ResultArray(1) is the OU the user belongs to

    regards from El Puño, Denmark

Leave your comment