# VBScript question about OU containers

**URL:** <https://boards.straightdope.com/t/vbscript-question-about-ou-containers/499883>\
**Category:** Factual Questions\
**Created:** [June 15, 2009, 10:28pm UTC](https://boards.straightdope.com/t/vbscript-question-about-ou-containers/499883 "2009-06-15T22:28:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![XT](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/xt/32/456_2.png) [@XT](https://boards.straightdope.com/u/XT)\
**Post date:** [June 15, 2009, 10:28pm UTC](https://boards.straightdope.com/t/vbscript-question-about-ou-containers/499883/1 "2009-06-15T22:28:04Z")

</div>

I need a hand with a VBScript I’m writing and know there are a few 'dopers who are VBScript programmers. Basically, I need some code that will determine what Organizational Unit (in Windows 2003 AD) a given user is in. If anyone can give me just a code snippet for it I would really appreciate it.

(I don’t have my own VBScript books with me and it’s really hard to do a search on my iPod)

-XT

---

<div class="post-metadata">

**Author:** ![Caldazar](https://avatars.discourse-cdn.com/v4/letter/c/8e8cbc/32.png) [@Caldazar](https://boards.straightdope.com/u/Caldazar)\
**Post date:** [June 15, 2009, 10:53pm UTC](https://boards.straightdope.com/t/vbscript-question-about-ou-containers/499883/2 "2009-06-15T22:53:02Z")

</div>

'Get the default naming context, or set it by hand if you like  
Set rootDSE=GetObject(“LDAP://RootDSE”)  
DomainContainer = rootDSE.Get(“defaultNamingContext”)

'Set up the AD connection  
Set objConn = CreateObject(“ADODB.Connection”)  
objConn.Provider = “ADSDSOObject”  
objConn.Open “Active Directory Provider”  
Set objCommand = CreateObject(“ADODB.Command”)  
Set objCommand.ActiveConnection = objConn

'Set the LDAP query, set the sAMAccountName in the string  
strQuery = “\<LDAP://” & DomainContainer & “\>;(sAMAccountName=CHANGETHIS);dn;subtree”  
objCommand.CommandText = strQuery

'Execute the LDAP query  
Set objRecordSet = objCommand.Execute

'Now do some more stuff that will read the RecordSet and parse the text string, which is the dn of sAMAccountName  
'Strip the leading “CN=…,” portion from the string, leaving the OU.
