title: VBscript search sAMAccountName from CN
body: <p>I've written this script which pulls the sAMAccountName of the specified user from the AD via VBscript, but it seems to only work within my own OU group. Is this due to a permissions restriction within my company? Or is this due to something i'm not seeing in the code?</p>
  
  <blockquote>
  <pre><code> Dim result
  result = getsAMAccountName("Some Name")
  msgbox result
  </code></pre>
  </blockquote>
  
  <pre><code>Function getsAMAccountName(name)
  Dim adoCommand, adoConnection, strBase, strFilter, strAttributes
  Dim objRootDSE, strDNSDomain, strQuery, adoRecordset, strsAM, objUser
  
  Set adoCommand = CreateObject("ADODB.Command")
  Set adoConnection = CreateObject("ADODB.Connection")
  adoConnection.Provider = "ADsDSOObject"
  adoConnection.Open "Active Directory Provider"
  Set adoCommand.ActiveConnection = adoConnection
  
  Set objRootDSE = GetObject("LDAP://RootDSE")
  strDNSDomain = objRootDSE.Get("defaultNamingContext")
  msgbox strDNSDomain
  strBase = "&lt;LDAP://" &amp; strDNSDomain &amp; "&gt;"
  
  'be sure passed var usersel is referenced properly
  strFilter = "(cn=" &amp; name &amp; ")"
  strAttributes = "distinguishedName"
  
  strQuery = strBase &amp; ";" &amp; strFilter &amp; ";" &amp; strAttributes &amp; ";subtree"
  adoCommand.CommandText = strQuery
  adoCommand.Properties("Page Size") = 100
  adoCommand.Properties("Timeout") = 30
  adoCommand.Properties("Cache Results") = False
  
  Set adoRecordset = adoCommand.Execute
  
  Do Until adoRecordset.EOF
  
      strsAM = adoRecordset.Fields("distinguishedName").Value
      Set objUser = GetObject("LDAP://" &amp; strsAM)
      getsAMAccountName = objUser.sAMAccountName
      adoRecordset.MoveNext
  Loop
  
  adoRecordset.Close
  adoConnection.Close
  End Function
  </code></pre>