Thursday, March 15, 2012

VB Script to get distinguishedName from AD

If you need to get the distinguishedName attribute from Active Directory you can use the script below.

You will need a list of users in c:\scripts\users.txt

The script will output to c:\scripts\dn.txt

OptionExplicit

Dim objRootDSE, strDomain, strUsername, objConnection, objCommand, objRecordSet, strDN
Dim objFSO, objFSO2, objTextFile, objTextFile2, strNextLine, arrUserList, i
Const ADS_SCOPE_SUBTREE = 2

' Get domain components
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")

'Setup Constants for input and output files
Const ForReading = 1
Const ForAppending = 8

'Open input file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\users.txt", ForReading)
'loop
DoUntil objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrUserList = Split(strNextLine , ",")
    'Wscript.Echo "User: " & arrUserList(0)
    
    ' Get username to search for
    strUsername = arrUserList(0)
    'Wscript.Echo strUsername
    ' Set ADO connection
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open"Active Directory Provider"

    ' Set ADO command
    Set objCommand = CreateObject("ADODB.Command")
    Set objCommand.ActiveConnection = objConnection
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.CommandText = "SELECT distinguishedName FROM 'LDAP://" & strDomain & "' WHERE objectCategory='user' AND samAccountName = '" & strUsername & "'"

    ' Set recordset to hold the query result
    Set objRecordSet = objCommand.Execute

    ' If a user was found - Retrieve the distinguishedName
    IfNot objRecordSet.EOFThen
        strDN = objRecordSet.Fields("distinguishedName").Value
            'Write to Output file
        Set objFSO2 = CreateObject("Scripting.FileSystemObject")
        Set objTextFile2 = objFSO2.OpenTextFile _
        ("c:\scripts\dn.txt", ForAppending, True)    
        objTextFile2.WriteLine(strDN)
        objTextFile2.Close
    Else
        'Can't find the user
        MsgBox"Username not found " & arrUserList(i)
    EndIf
Loop
MsgBox"Finished getting DN for usernames check c:\scripts\dn.txt"

1 comment:

  1. Harrah's Cherokee Casino & Hotel - JT Hub
    Situated near the mountains, this 정읍 출장안마 hotel features an outdoor 구리 출장마사지 pool 청주 출장안마 and a 안동 출장샵 Jacuzzi. 서울특별 출장안마 Each room is deluxe-sized with a king size bed.

    ReplyDelete