Solved

Find user object in Active Directory (VBS)

Posted on 2010-09-23
7
2,999 Views
Last Modified: 2012-05-10
Hey

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

Thanks
0
Comment
Question by:mikeydk
7 Comments
 
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"
or
dsquery user -samid "login"

These command works on servers or workstations with administrative tools installed
0
 

Expert Comment

by:blacksatin
ID: 33741982
See helper class in attach

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

ActiveDirectoryHelper.cs
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 167 total points
ID: 33742106
Hi, here's some VBS that I often use.

Regards,

Rob.
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

Else

	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)

      Else

      ' 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

                Else

                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value

                End If

          Next

          ' Move to the next record in the recordset.

          adoRecordset.MoveNext

      Loop



      ' Clean up.

      adoRecordset.Close

      adoConnection.Close

      Get_LDAP_User_Properties = strReturnVal



End Function

Open in new window

0
 
LVL 17

Assisted Solution

by:Tony Massa
Tony Massa earned 167 total points
ID: 33745245
Find more here:  http://www.rlmueller.net/NameTranslateFAQ.htm

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

Const ADS_NAME_TYPE_NT4 = 3

Const ADS_NAME_TYPE_1779 = 1

Const ADS_PROPERTY_CLEAR = 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

0
 
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
$searcher.Filter="(&(objectcategory=person)(objectclass=user)(sAMAccountname="+$sam+"))"
$results=$searcher.FindOne()
if ($results.path.length -gt 1)
     {
     return $results
     }
    else
     {
     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."
    }
    else
    {
     $objUser=$User.GetDirectoryEntry()
     Write-Host `n
     Write-Host "DN is"$objUser.DistinguishedName
     Write-host "UPN is"$objUser.UserPrincipalName
     Write-host `n
     Write-Host "Other available properties:"
     $objUser|Get-Member
    }
0
 
LVL 12

Expert Comment

by:Daz_1234
ID: 33752482
Hi,

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,
Daz


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
Else
    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")
        objRecordSet.MoveNext
    Loop
    fGetUserDN = sDN
End Function

Open in new window

0
 

Author Closing Comment

by:mikeydk
ID: 33989880
Super
0

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  (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_28455246.html)28455246) 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