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

Jerold Schulman

March 22, 2006

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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 FolderFindUser.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 FolderFindUser.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 NextDim objConnection, objCommand, objRootDSE, strDNSDomainDim strFilter, strQuery, objRecordSet, objArgs, usrSet objArgs = Wscript.Argumentsif objArgs.Count  1 Then Wscript.Echo "FindUser UserName - UserName required."if objArgs.Count  1 Then Wscript.Quitusr = "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 = objConnectionSet objRootDSE = GetObject("LDAP://RootDSE") strDNSDomain = objRootDSE.Get("defaultNamingContext") strBase = "" strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sam & "))" strAttributes = "distinguishedName,sAMAccountName"strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"objCommand.CommandText = strQueryobjCommand.Properties("Page Size") = 99999objCommand.Properties("Timeout") = 300objCommand.Properties("Cache Results") = FalseSet objRecordSet = objCommand.ExecuteobjRecordSet.MoveFirstDo Until objRecordSet.EOF    strDN = objRecordSet.Fields("distinguishedName")     strSAM = objRecordSet.Fields("sAMAccountName")    usr = "Y"    Wscript.Echo strSAM & " 

& strDN &

"    objRecordSet.MoveNextLoopobjConnection.CloseSet objConnection = Nothingif usr = "N" Then Wscript.Echo "FindUser " & sam & " - NOT found."Set objCommand = NothingSet objRootDSE = NothingSet objRecordSet = Nothing



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like