VBS Script and using variables - TechRepublic
Question
May 23, 2008 at 10:09 AM
matt.johnstone

VBS Script and using variables

by matt.johnstone . Updated 18 years, 1 month ago

Hello everyone,

I don’t have much scripting experience, but I’ve managed to build one for searching Active Directory for a given username. What I’m looking to do is have the user prompted for his/her username and have that variable used for the search. I’ve gotten that worked out, but what i can’t figure out is using the variable in the following code

‘Find Full Name from login name
objCommand.CommandText = _
“SELECT Name FROM ‘LDAP://dc=xxx,dc=xxx,dc=com’ WHERE objectCategory=’user’ ” & _
“AND sAMAccountName=’gptest'”
Set objRecordSet = objCommand.Execute

WScript.Echo “Full Name is ” & objRecordset.Fields(“Name”).value

Where it says “AND sAMAccountName=’gptest'”, if I replace gptest with the variable strUserName the code errors out.
I’ve tried sAMAccountName=strusername SamAccountName=’strusername’
SamAccountName= & strusername
and a few others.

I’ll put the whole code up for reference. It will be trimmed down some when its ready to be deployed, right now its just in the ‘new coder play with everything’ phase. Any suggestions on how to insert the variable in there are welcome!

dim strusername
strUserName = “gptest” ‘once the rest of the ‘script works this will be replaced with the ‘prompt code
dtStart = TimeValue(Now())
Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”

Set objCommand = CreateObject(“ADODB.Command”)
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
;(&(objectCategory=User)” & _
“(samAccountName=” & strUserName & “));samAccountName;subtree”

Set objRecordSet = objCommand.Execute

If objRecordset.RecordCount = 0 Then
WScript.Echo “sAMAccountName: ” & strUserName & ” does not exist.”

Else
WScript.Echo strUserName & ” exists.”

‘Find Full Name from login name
objCommand.CommandText = _
“SELECT Name FROM ‘LDAP://dc=xxx,dc=xxx,dc=com’ WHERE objectCategory=’user’ ” & _
“AND sAMAccountName=’gptest'”
Set objRecordSet = objCommand.Execute

WScript.Echo “Full Name is ” & objRecordset.Fields(“Name”).value

‘Find login Script for user
objCommand.CommandText = _
“SELECT ScriptPath FROM ‘LDAP://dc=xxx,dc=xxx,dc=com’ WHERE objectCategory=’user’ ” & _
“AND sAMAccountName=’gptest'”
Set objRecordSet = objCommand.Execute
Wscript.Echo “Script Path: ” & objRecordset.Fields(“ScriptPath”).value

‘ Wscript.Echo “Home Directory: ” & objUser.HomeDirectory
‘ Wscript.Echo “Home Drive: ” & objUser.HomeDrive
End If

EDIT: Apologies for the format of the code, Forum box altered it slightly.

This discussion is locked

All Comments