Apologies for not using a more creative title but I couldn't think of one (it's been a long day).

I'm having trouble with this particular function, I can't give credit (I didn't write it) as there is no information in the routine itself as to who wrote it.

However the problem I'm having is the function is designed to search AD for a given object ($type) with name ($cn) starting in the LDAP root ($root) and finally looking for a particular attribute ($attribute).

What I'm having difficulty with is that some users are found by the script but some are not, yet a search using the AD MMC (Users and Computers) shows me exactly where they are.

Basically what I want to do is to have a function search the AD tree starting at the root ($root), for a particular username ($cn) - if it doesn't find it, return nothing. If it finds it, return the DN of the object found (as parts later in my script rely on this).

The problem with this is it doesn't seem to search ALL the AD users, it seems to get 3/4 of them and then just gives up (we have 1500+ users). Does anyone have any ideas why this is, or does anyone have any clue as to how I could write a function that does exactly what I want, or does anyone have a UDF for this? I've look around and can't seem to find anything that does this specifically.

Thanking you all in advance.

Code:

Function searchAD( $root, $cn, $type, $attribute )
$objConnection = CreateObject( "ADODB.Connection")
$objConnection.Open( "Provider=ADsDSOObject;")
$objCommand = CreateObject( "ADODB.Command")
$objCommand.ActiveConnection = $objConnection
$objCommand.Commandtext = ";(objectCategory=$Type);distinguishedName,$attribute;subtree"
$objRecordSet = $objCommand.Execute

While NOT $objRecordSet.EOF
If CStr( $objRecordSet.Fields( $attribute ) ) = $cn
$searchAD = CStr( $objRecordSet.Fields( "distinguishedName" ) ) ; Returns the LDAP string if object is found
Exit
Else
$searchAD = 0 ; Otherwise, it returns a Zero
EndIf
$objRecordSet.MoveNext
Loop
EndFunction