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!


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

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