Find user object in Active Directory (VBS)

Posted on 2010-09-23
Last Modified: 2012-05-10

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")

Question by:mikeydk
LVL 39

Expert Comment

by:Krzysztof Pytko
ID: 33741770
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

Expert Comment

ID: 33741982
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"/>

LVL 65

Accepted Solution

RobSampson earned 167 total points
ID: 33742106
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

LVL 17

Assisted Solution

by:Tony Massa
Tony Massa earned 167 total points
ID: 33745245
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

LVL 12

Assisted Solution

by:Anuradha Goli
Anuradha Goli earned 166 total points
ID: 33747889
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:"
LVL 12

Expert Comment

ID: 33752482

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


Author Closing Comment

ID: 33989880

Join & Write a Comment

Not long ago I saw a question in the VB Script forum that I thought would not take much time. You can read that question (Question ID  ( Here (http…
Find out how to use Active Directory data for email signature management in Microsoft Exchange and Office 365.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now