JSI Tip 10140. How can a VBScript return the distinguishedName(s) of all user's that match a specific CN?


I have scripted a LDAP (Lightweight Directory Access Protocol) query named FindUserCN.vbs to return multiple Active Directory objects in your domain that match a CN filter parameter.

NOTE: See tip 10015 ยป How can I use VBScript to return all the users in an OU (Organizational Unit)?

The syntax for using FindUserCN.vbs is:

cscript //nologo c:\util\FindUserCN.vbs "User CN Parameter"

Examples:

cscript //nologo c:\util\FindUserCN.vbs "* DOE*"

returns:

"CN=John Doe,CN=Users,DC=JSIINC,DC=COM"
"CN=Jane Doe,CN=Users,DC=JSIINC,DC=COM"


cscript //nologo c:\util\FindUserCN.vbs "Jerold Schulman"

returns:

"CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM"
"CN=Jerold Schulman,OU=OU_TEST,DC=JSIINC,DC=COM"
FindUserCN.vbs contains:
On Error Resume Next
Dim objConnection, objCommand, objRootDSE, strDNSDomain
Dim strFilter, strQuery, objRecordSet, objArgs
Set objArgs = Wscript.Arguments
if objArgs.Count = 0 then 
 Wscript.Echo  "CN argument required. ""*"" or ""J*"" or etc.."
 WScript.Quit (1)
End If
cn = objArgs(0)
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOOBject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strBase = "<LDAP://" & strDNSDomain & ">"
strFilter = "(&(objectCategory=person)(objectClass=user)(cn=" & cn & "))"
strAttributes = "distinguishedName"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 99999
objCommand.Properties("Timeout") = 300
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    strDN = objRecordSet.Fields("distinguishedName")
    Wscript.Echo 
" & strDN &
" objRecordSet.MoveNext Loop objConnection.Close Set objConnection = Nothing Set objCommand = Nothing Set objRootDSE = Nothing Set objRecordSet = Nothing



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish