Find user object in Active Directory (VBS)


I only have the username... I have to find the exact user object path - so I can use the GetObject

ex. Set objUser = GetObject("LDAP://MySvr/cn=Joe,cn=users,dc=MyDom,dc=com")

Who is Participating?

Improve company productivity with a Business Account.Sign Up

RobSampsonConnect With a Mentor Commented:
Hi, here's some VBS that I often use.


strUsername = InputBox("Enter a username to find the ADsPath for:", "Username")
strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adsPath")
If Left(strUserADsPath, 7) = "LDAP://" Then
	Set objUser= GetObject(strUserADsPath)
	MsgBox "Successfully bound to " & strUserADsPath
	MsgBox "Could not find adsPath for " & strUsername
End If

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '				It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '				For example, if you are searching based on the user account name, strSearchField
      '				would be "samAccountName", and strObjectToGet would be that speicific account name,
      '				such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '	strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '				the home folder path, as defined by the AD, for a specific user, this would be
      '				"homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '				user and get your own parameters from them, then use "ADsPath" as a return string,
      '				then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If

      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection

      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")

      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False

      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          ' Move to the next record in the recordset.

      ' Clean up.
      Get_LDAP_User_Properties = strReturnVal

End Function

Open in new window

Krzysztof PytkoSenior Active Directory EngineerCommented:
you can use dsquery to fulfill these requirements but I'm affraid that you want to use some command inside your VBS file to catch this value and put in other field?

If not, you can determine exact path using dsquery

dsquery user -name "Full Name"
dsquery user -samid "login"

These command works on servers or workstations with administrative tools installed
See helper class in attach

 private readonly app.auth.DAL.DAL_AD dal_ad = new app.auth.DAL.DAL_AD(
                                                            new ActiveDirectoryHelper()
 public bool CheckUser(string UserName)
      return adh.UserExists(UserName, "userPrincipalName");
            <add key="LDAPDomain" value="aaa.bbb"/>
            <add key="LDAPPath" value="LDAP://"/>
            <add key="LDAPUser" value="aaa\ddd"/>
            <add key="LDAPPassword" value="fff"/>

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Tony MassaConnect With a Mentor Commented:
Find more here:

Here's a sample script to get the user's email address if you enter a sAMAccountName
Const ADS_NAME_TYPE_1779 = 1

strNetBIOSDomain = "DOMAIN"
strUserID = Inputbox("Enter the user's logon ID: ", "User Information")

On Error Resume Next
' Use the NameTranslate object to convert the NT user name to the
' Distinguished Name required for the LDAP provider.
Set objTrans = CreateObject("NameTranslate")

' Initialize NameTranslate by locating the Global Catalog.
objTrans.Init ADS_NAME_INITTYPE_GC, ""
' Use the Set method to specify the NT format of the object name.
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strUserID

' Use the Get method to retrieve the RPC 1779 Distinguished Name.
strUserDN = objTrans.Get(ADS_NAME_TYPE_1779)

Set objUser = GetObject("LDAP://" & strUserDN)

strEmailAddress = objUser.mail

Wscript.Echo strUserDN & vbCRLF & vbCRLF & "Email Address: " & strEmailAddress

Open in new window

Anuradha GoliConnect With a Mentor Systems Development / Support SpecialistCommented:
function Find-User
Param ($sam=$(throw "you must enter a sAMAccountname"))
$searcher=New-Object DirectoryServices.DirectorySearcher
if ($results.path.length -gt 1)
     return $results
     return "Not Found"
 $sam=Read-Host "Enter a sAMAccountname"
 $User=Find-User $sam
 if ($User -eq "Not Found")
     Write-Host -foregroundcolor RED $sam.ToUpper() "was not found in the directory."
     Write-Host `n
     Write-Host "DN is"$objUser.DistinguishedName
     Write-host "UPN is"$objUser.UserPrincipalName
     Write-host `n
     Write-Host "Other available properties:"

I have written a self-contained function below, fGetUserDN(sSAMAccountName),  that should get the DN of any user from any domain (certainly it works on the 2 that I tried it on without amendment).

The script pasted below also shows sample useage.

Hope this helps,

Option Explicit

Dim strUser, strUserDN, strLDAP

strUser = "ictt0015"

strUserDN = fGetUserDN(strUser)

If InStr(1, strUserDN, "Not Found", 1) = 0 Then
    strLDAP = "LDAP://MySvr/"  & strUserDN
    MsgBox strLDAP,,strUser
    MsgBox strUserDN
End If

Function fGetUserDN(sSAMAccountName)
    Dim objRootDSE, strDNSDomain, strConfig, objCommand, objConnection, strBase
    Dim strFilter, strAttributes, strQuery, objRecordSet, strDCs, sDN
    Set objRootDSE = GetObject("LDAP://RootDSE")
    strDNSDomain = objRootDSE.Get("defaultNamingContext")
    Set objCommand = CreateObject("ADODB.Command")
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open = "ADProvider"
    objCommand.ActiveConnection = objConnection

    strBase = "<LDAP://" & strDNSDomain & ">"
    strFilter = "(&(objectCategory=person)(sAMAccountName=" & sSAMAccountName & "))"
    strAttributes = "distinguishedName"
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"

    objCommand.CommandText = strQuery
    objCommand.Properties("Cache Results") = False

    sDN = "User '" & sSAMAccountName & "' Not Found"
    Set objRecordSet = objCommand.Execute
    Do Until objRecordSet.EOF
        sDN = objRecordSet.Fields("distinguishedName")
    fGetUserDN = sDN
End Function

Open in new window

mikeydkAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.