VBS Script to run a Query against a Active Directory Domain

The below script is an example of how using VBS and ADODB you can perform SQL like queries against Active directory to return or change properties of an object.

In this case the script returns the “Home Drive” on the user “testusername” in the domain “domainname.com”

' --------------------------------------------------------
' VBS Script to run a Query againt a Active Directory Domain
'
' Author: Phil Eddies
' https://geekshangout.com
'
' Disclainer:
' Use of this script / software is entirely at your own risk no support, warranty 
' or guaranty is given.
' 
' The author or GeeksHangout.com take not responsibility for any damage or problems
' caused by this script / software.
'
' Copyright 2008 Philip Eddies
'
' Licensed under GPL
'    This program is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 3 of the License, or
'    (at your option) any later version.'
'
'    This program is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.'
'
'    You should have received a copy of the GNU General Public License
'    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'
' --------------------------------------------------------
 
 
 
On Error Resume Next
 
Const ADS_SCOPE_SUBTREE = 2
 
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = ("ADsDSOObject")
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
objCommand.CommandText =  "SELECT sAMAccountName, homeDirectory FROM 'LDAP://dc=domainname,dc=com' WHERE objectCategory='user' AND sAMAccountName='testusername'"
 
objCommand.Properties("SearchScope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
 
If objRecordSet.RecordCount = 0 Then
    Wscript.Echo "The samAccount was not found"
Else
    Wscript.Echo "The user Home drive is: " & objRecordSet.Fields("homeDirectory").Value
End If

 

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.