'==========================================================================
'
' VBScript:  AUTHOR: Ed Wilson , MS,  6/25/2006
'
' NAME: <QueryGC.vbs>
'
' COMMENT: Key concepts are listed below:
'1.Uses a function to clean up the input from Variables. All query parameters
'2.are put into variables that are easy to edit. These are then put together 
'3.to create the query. The function creates the GC connection string. 
'==========================================================================
Option Explicit    	     
'On Error Resume Next 
Dim strQuery 				'Holds query to execute
Dim objConnection 	'Makes connection to active directory
Dim objCommand 			'Executes the query
Dim objRecordSet 		'Holds the data returned from the query
Dim strDomain				'Domain to work with
Dim strField				'Attributes to select
Dim strDepth				'Depth of the query
Dim strProvider			'Provider to use
Dim strFilter				'LDAP syntax Filter
Dim strOU						'OU to connect to. VBempty if none used
Dim aryFields				'From split
Dim field 					'Individual field in array

strDomain = "nwtraders.msft" 					'Can handle MultipleLevelDomain
strOU 		= "ou=mred" 								'Set to vbempty if no ou desired. NO QUOTE for vbempty
strDomain = funfix(strOU,strDomain)
strField 	= "name,distinguishedName" 	'Just add attributes here. Separate by , NO trailing ,
strDepth 	= "subTree"
strFilter = "(objectCategory=user)" 	'Ex: (objectCategory=user). Or "" for no filter.
strQuery 	= strDomain & ";" & strFilter &  ";" & _
					 strField & ";" & strDepth
strProvider = "Provider=ADsDSOObject;"

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Open strProvider
objCommand.ActiveConnection = objConnection
objCommand.CommandText = strQuery
Set objRecordSet = objCommand.Execute

aryFields = Split(strField,",")

While Not objRecordSet.EOF
	For Each field In aryFields
    Wscript.Echo objRecordSet.Fields(field)
	next
    objRecordSet.MoveNext
Wend

objConnection.Close


' **** Functions below ******
Function funfix(strOU,strIN)
Dim i 		'counter used to tell if at end of array
Dim aryIN	'created by split
Dim strDC	'the comain component lines

i=0
aryIN=Split(strIN,".")
For Each strDC In aryIN
	funfix = funfix & "dc=" & strDC
	If i < UBound(aryIN) Then funfix = funfix & ","
	i = i+1
Next
If strOU <> vbempty Then
funfix = "<GC://" & strOU & "," & funfix & ">"
else
funfix = "<GC://" & funfix & ">"
End if
End Function