Search code examples
asp-classicvbscriptactive-directory

VBscript search sAMAccountName from CN


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?

 Dim result
result = getsAMAccountName("Some Name")
msgbox result
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 = "<LDAP://" & strDNSDomain & ">"

'be sure passed var usersel is referenced properly
strFilter = "(cn=" & name & ")"
strAttributes = "distinguishedName"

strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";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://" & strsAM)
    getsAMAccountName = objUser.sAMAccountName
    adoRecordset.MoveNext
Loop

adoRecordset.Close
adoConnection.Close
End Function

Solution

  • Ended up being permissions, be sure to include/specify a processID and PW when moving LDAP pulls to asp classic... and avoid asp classic

    Set adoConnection = CreateObject("ADODB.Connection")                
                adoConnection.Provider = "ADsDSOObject"
                    With adoConnection
                        .Properties("User ID") = ' Process ID goes
                        .Properties("Password") = 'password
                        .Properties("encrypt password") = True
                    End With
    
            adoConnection.Open "Active Directory Provider"
            Set adoCommand = CreateObject("ADODB.Command")
            Set adoCommand.ActiveConnection = adoConnection