Solved

vbscript ldap query for office

Posted on 2011-02-16
1
996 Views
Last Modified: 2012-05-11
I am familiar with programming, but am not a programmer.  What I am attempting to do is use a VBScript to lookup a user (by samaccount name) and write their office (physicalDeliveryOfficeName) to a text file.

My users are spread across quite a few OU's so I know that I need to write it as a query with filters.  The only portion of my script that I have pretty much "set" is the write to file.  The actual LDAP portion of it I don't really have anything.  I have tried modifying quite a few different scripts but something keeps going wrong - and I can't seem to extract the portion that would make what I need work (I have about 4 different not-working versions, figured rather than posting all of those I would just not post that portion of the code).


Dim Office, myFSO, WriteOffice

'Write information to Text File
office = strphysicalDeliveryOfficeName

Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteOffice = myFSO.OpenTextFile("c:\temp data\efax\office.txt", 8, True)
WriteStuff.WriteLine(Stuff)
WriteStuff.Close
SET WriteStuff = NOTHING
SET myFSO = NOTHING
0
Comment
Question by:americaneldercare
1 Comment
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 34911545
Hi there, this script will do the job.  I have taken input of samAccountNames from a text file, but you could of course, just run the report over your entire AD anyway, but I think you wanted to take them as input.

Regards,

Rob.
strInput = "samaccountnames.txt"
strOutput = "userOfficeNames.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set objInput = objFSO.OpenTextFile(strInput, ForReading, False)
Set objOutput = objFSO.CreateTextFile(strOutput, True)
objOutput.WriteLine """samAccountName"",""distinguishedName"",""physicalDeliveryOfficeName"""

While Not objInput.AtEndOfStream
	strSamAccountName = objInput.ReadLine
	If strSamAccountName <> "" Then
		strProperties = Get_LDAP_User_Properties("user", "samaccountname", strsamAccountName, "distinguishedName,physicalDeliveryOfficeName")
		If strProperties <> "" Then
			objOutput.WriteLine """" & strSamAccountName & """,""" & Replace(strProperties, VbCrLf, """,""") & """"
		Else
			objOutput.WriteLine """" & strSamAccountName & """,""NOT FOUND"",""NOT FOUND"""
		End If
	End If
Wend
objInput.Close
objOutput.Close

MsgBox "Done. Please see " & strOutput

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Learn about cloud computing and its benefits for small business owners.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

757 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

22 Experts available now in Live!

Get 1:1 Help Now