Skip navigation

JSI Tip 10307. How can I use Vbscript to determine if a user logon name (sAMAccountName) exists in my domain?

I have scripted FindUser.vbs to determine if a user logon name exists in the logged on domain.

The syntax for using FindUser.vbs is:

cscript //nologo <Drive:>\Folder\FindUser.vbs sAMAccountName

Where sAMAccountName is the user logon name, like Jerry.

If Jerry exists in the domain, FindUser.vbs will echo sAMAccountName "distinguishedName", like:

Jerry "CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM"

If Jerry DOES NOT exists in the domain, FindUser.vbs will echo FindUser sAMAccountName - NOT found., like:

FindUser Jerry - NOT found.

If you run cscript //nologo <Drive:>\Folder\FindUser.vbs J*, FindUser.vbs will echo all the matching logon names with their distinguished names, like:

Jane.Doe "CN=Jane Doe,CN=Users,DC=JSIINC,DC=COM"
Jennifer "CN=Jennifer Schulman,CN=Users,DC=JSIINC,DC=COM"
Jerry "CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM"
John.Doe "CN=John Doe,CN=Users,DC=JSIINC,DC=COM"
Jordan.Valley "CN=Jordan Valley,CN=Users,DC=JSIINC,DC=COM"
FindUser.vbs contains:
On Error Resume Next
Dim objConnection, objCommand, objRootDSE, strDNSDomain
Dim strFilter, strQuery, objRecordSet, objArgs, usr
Set objArgs = Wscript.Arguments
if objArgs.Count  1 Then Wscript.Echo "FindUser UserName - UserName required."
if objArgs.Count  1 Then Wscript.Quit
usr = "N"
sam = 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)(sAMAccountName=" & sam & "))" 
strAttributes = "distinguishedName,sAMAccountName"
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") 
    strSAM = objRecordSet.Fields("sAMAccountName")
    usr = "Y"
    Wscript.Echo strSAM & " 
& strDN &
" objRecordSet.MoveNext Loop objConnection.Close Set objConnection = Nothing if usr = "N" Then Wscript.Echo "FindUser " & sam & " - NOT found." 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