vbscript, validate a user is in active directory by schema attribute - vbscript

I'm trying to write a vb script that prompts a user for a schema attribute which I'll call bID and checks that the person with that bID is in active directory. I really have no idea how to get started, there are plenty of examples on how to query active directory users but I havent found a good one regarding checking against specific attributes. Any help/suggestions are greatly appreciated!
UPDATE:
ok heres my code so far, doesnt error out and returns 0, but I dont get a wscript.echo of the distinguished name for some reason. I included a few debugging wscript.echo's and it seems to never get into the while loop. Any ideas?
Option Explicit
GetUsers "CN=users,DC=example,DC=example,DC=example,DC=com","123456"
Function GetUsers(domainNc, ID)
Dim cnxn
Set cnxn = WScript.CreateObject("ADODB.Connection")
cnxn.Provider = "ADsDSOObject"
cnxn.Open "Active Directory Provider"
Dim cmd
Set cmd = WScript.CreateObject("ADODB.Command")
cmd.ActiveConnection = cnxn
cmd.CommandText = "<LDAP://" & domainNc & ">;(&(objectCategory=user)(objectClass=user) (employeeNumber=" & ID & "));distinguishedName;subtree"
WScript.Echo cmd.CommandText
cmd.Properties("Page Size") = 100
cmd.Properties("Timeout") = 30
cmd.Properties("Cache Results") = False
WScript.Echo "setting cmd.properties"
Dim rs
Set rs = cmd.Execute
WScript.Echo "rs object set"
While Not rs.eof
On Error Resume Next
WScript.Echo "while loop start"
Wscript.Echo rs.fields("distinguishedName".Value)
rs.MoveNext
If (Err.Number <> 0) Then
WScript.Echo vbCrLf& "Error # "& CStr(Err.Number)& " "& Err.Description
Else
On Error GoTo 0
End If
Wend
WScript.Echo "while loop end"
rs.close
WScript.Echo "rs object closed"
cnxn.Close
Set rs = Nothing
Set cmd = Nothing
Set cnxn = Nothing
End Function

Here's some vbscript that will find all users with bID=FooVal and write their DN out
Function GetUsers(domainNc, bIdVal)
Dim cnxn
Set cnxn = WScript.CreateObject("ADODB.Connection")
cnxn.Provider = "ADsDSOObject"
cnxn.Open "Active Directory Provider"
Dim cmd
Set cmd = WScript.CreateObject("ADODB.Command")
cmd.ActiveConnection = cnxn
cmd.CommandText = "<LDAP://" & domainNc & ">;(&(objectCass=user)(objectCategory=person)(bid=" & bidVal & "));distinguishedName;subtree"
cmd.Properties("Page Size") = 100
cmd.Properties("Timeout") = 30
cmd.Properties("Cache Results") = False
Dim rs
Set rs = cmd.Execute
While Not rs.eof
Wscript.Echo rs.fields("distinguishedName").Value
rs.MoveNext
Wend
rs.close
cnxn.Close
Set rs = Nothing
Set cmd = Nothing
Set cnxn = Nothing
End Function

Related

How can I Detect an ADO Connection Error? [duplicate]

When a SQL batch returns more than one message from e.g. print statements, then I can only retrieve the first one using the ADO connection's Errors collection. How do I get the rest of the messages?
If I run this script:
Option Explicit
Dim conn
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "SQLOLEDB"
conn.ConnectionString = "Data Source=(local);Integrated Security=SSPI;Initial Catalog=Master"
conn.Open
conn.Execute("print 'Foo'" & vbCrLf & "print 'Bar'" & vbCrLf & "raiserror ('xyz', 10, 127)")
Dim error
For Each error in conn.Errors
MsgBox error.Description
Next
Then I only get "Foo" back, never "Bar" or "xyz".
Is there a way to get the remaining messages?
I figured it out on my own.
This works:
Option Explicit
Dim conn
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "SQLOLEDB"
conn.ConnectionString = "Data Source=(local);Integrated Security=SSPI;Initial Catalog=Master"
conn.Open
Dim rs
Set rs = conn.Execute("print 'Foo'" & vbCrLf & "print 'Bar'" & vbCrLf & "raiserror ('xyz', 10, 127)")
Dim error
While not (rs is nothing)
For Each error in conn.Errors
MsgBox error.Description
Next
Set rs = rs.NextRecordSet
Wend

Test ADO connection and reconnect prior to execution if needed, in VBScript

I have the following VBScript (vbs):
Option Explicit
Dim cn, cmDB, rs
Set cn = CreateObject("ADODB.Connection")
cn.ConnectionString = "DSN=PostgreSQLDNSHere"
cn.Open
cn.CommandTimeout = 28800
Set cmDB = CreateObject("ADODB.Command")
cmDB.CommandTimeout = 28800
Set rs = CreateObject("ADODB.Recordset")
rs.CursorType = 2
MsgBox "disconnected network here then clicked ok to proceed"
MsgBox cn.State
MsgBox cmDB.State
MsgBox rs.State
Set rs = cn.Execute("select * from test;")
WScript.Quit
At the first message box I would like to simulate losing a connection to our database. Possible causes could be that the database is down or the LAN is down, etc. In other words, I want to test if the connection is in good order so a valid execute statement will succeed. The msgboxes above never change after I disconnect from the network.
The only way I can currently do it is to Execute after a On Error Resume Next, then look at the Err.Number. Is there a way to test the connection prior to the execute so I can reconnect then execute like this:
Option Explicit
Dim cn, cmDB, rs
Set cn = CreateObject("ADODB.Connection")
cn.ConnectionString = "DSN=PostgreSQLDNSHere"
cn.Open
cn.CommandTimeout = 28800
Set cmDB = CreateObject("ADODB.Command")
cmDB.CommandTimeout = 28800
Set rs = CreateObject("ADODB.recordset")
rs.CursorType = 2
MsgBox "disconnected network here then clicked ok to proceed"
If cn.State = ?? Then
'reconnect here
End If
Set rs = cn.Execute("select * from test;")
WScript.Quit
EDIT1:
I also tried setting the recordset after disconnect, but that didn't change the message box result in the first code snippet.
The State property indicates just the state of the connection on the client side. AFAIK you need to execute a query in order to detect whether or not the server is still available.
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = cn
cmd.CommandText = "SELECT 1;"
On Error Resume Next
Set rs = cmd.Execute
If Err Then
If Err.Number = &h80004005 Then
'server side disconnected -> re-open
cn.Close
cn.Open
Else
WScript.Echo "Unexpected error 0x" & Hex(Err.Number) & ": " & Err.Description
WScript.Quit 1
End If
End If
Note that you may need to re-assign the re-opened connection to the object using it.
Note also that the above does just the most basic reconnect by closing and re-opening the connection. In real-world scenarios you may want to be able to retry at least a couple times if the reconnect fails as well (e.g. because the network or server hasn't come back up yet).
Using Ansgar's suggestion I am posting code that will "try at least a couple times". The function will return the connection object if it successfully reconnects or the connection is already good, else nothing after trying a user input number of times and waiting a user input number of seconds between tries:
Option Explicit
dim cn, cmDB, rs
set cn = CreateObject("ADODB.Connection")
cn.ConnectionString= "DSN=PostgreSQLDsn"
cn.open
cn.CommandTimeout = 28800
Set cmDB = CreateObject("ADODB.Command")
cmDB.CommandTimeout = 28800
set rs = CreateObject("ADODB.recordset")
rs.CursorType = 2
msgbox "disconnected internet here then clicked ok to proceed"
set cn = TestReOpenConnection(cn,"DSN=PostgreSQLDsn",28800,2,100)
if cn is nothing then
msgbox "not good"
WScript.Quit
end if
set rs = cn.execute("select * from test;")
msgbox "all good: " & rs.fields("x")
WScript.Quit
function TestReOpenConnection(cn,sDsn,iConnTimeOut,iWaitSecs,iTimesToTry)
dim iWaitMilSecs
iWaitMilSecs = iWaitSecs * 1000
dim bConnected
bConnected = false
dim iTries
iTries = 0
dim rsTest
set rsTest = CreateObject("ADODB.recordset")
do while bConnected = false
On Error Resume Next
Set rsTest = cn.execute("select 1;")
If Err Then
if iTries <> 0 then
WScript.Sleep iWaitMilSecs 'if we tried once already, then wait
end if
cn.Close
set cn = CreateObject("ADODB.Connection")
cn.ConnectionString= sDsn
On Error Resume Next
cn.open
cn.CommandTimeout = iConnTimeOut
else
bConnected = true
set TestReOpenConnection = cn
End If
iTries = iTries + 1
if iTries > iTimesToTry then
set TestReOpenConnection = nothing
exit do
end if
loop
end function
This answer isn't necessary to the central question I asked, but I thought it would be useful to people viewing this in the future. Probably could use some cleaning up.

Put DN into variable VBS

I am creating a script that will allow me to enter a username in our domain, and have it look up attributes from their AD profile.
So first I am getting the users' DN. Once I have that - I can run;
Set objAD = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & ***I NEED DN HERE***)
and query specific attributes to be output.
So what I need to do is somehow get the DN into a variable to put into the LDAP query. I know (I think) I need to get it from the Do Loop below, but am having a complete blank and can't figure out how to just put the whole DN into a variable.
Username = InputBox("Enter UserName to lookup...")
Set rootDSE = GetObject("LDAP://RootDSE")
base = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"
fltr = "(&(objectClass=user)(objectCategory=Person)" & "(sAMAccountName=" & UserName & "))"
attr = "distinguishedName,sAMAccountName"
scope = "subtree"
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = base & ";" & fltr & ";" & attr & ";" & scope
Set rs = cmd.Execute
Do Until rs.EOF
WScript.Echo rs.Fields("distinguishedName").Value
rs.MoveNext
Loop
rs.Close
conn.Close
In case anyone has the same problem - it was an easy fix.
Just needed to write it to a variable instead of echoing.
Do Until rs.EOF
strDN = rs.Fields("distinguishedname").value
rs.MoveNext
Loop

VBScript code error when using ActiveX to get data from the database

Here is my code, I am trying to open a connection to our database and then using ActiveX to return all the data from column in a table and then outputting it to a text document. I'm getting this error.
PullData.vbs(41, 1) ADODB.Recordset: Item cannot be found in the
collection corresponding to the requested name or ordinal.
Here is my code, omitting sensitive information:
Const ForReading = 1
Dim sServer
Dim sLogin
Dim sPwd
Dim sDb
Dim oCn
Dim oRs
sServer = ""
sLogin = ""
sPwd = ""
sDb = ""
Set oCn = CreateObject( "ADODB.Connection" ) ' set oCn to create an object called ADODB.Connection
Set oRs = CreateObject( "ADODB.Recordset" ) ' set oRs to create an object called ADODB.Recordset
oCn.ConnectionString = "PROVIDER=SQLOLEDB" & _
";SERVER=" & sServer & _
";UID=" & sLogin & _
";PWD=" & sPwd & _
";DATABASE=" & sDb & " "
oCn.ConnectionTimeout=600
oCn.open 'Open the connection to the server
strSelString = "select CallID from dbo.CallLog" 'this is the SQL statement that runs a query on the DB
oRs.Open strSelString,oCn 'This opens the record set and has two parameters, strSelString and oCn
If oRs.EOF Then 'If open record set is at the end of file then...
wscript.echo "There are no records to retrieve; Check that you have the correct record number." 'echo that there is no records to retrieve.
End if
'if there are records then loop through the fields
Do While Not oRs.EOF ' Do while not open record set is not end of file
strfield = ors("Tracker")
if strfield <> "" then 'If strfield doesn't equal "" then
Set objFileSystem = WScript.CreateObject("Scripting.FileSystemObject") 'Set objFileSystem to create object Scripting.FileSystemObject
Set objOutPutFile = objFileSystem.CreateTextFile("c:\test.txt", True) 'Set objOutPutFile to create object objFileSystem.CreateTextFile
strcomputer = oRs 'strcomputer is set to read the line
wscript.echo strfield
objOutPutFile.WriteLine strfield &"|"
objFileSystem.close
objOutPutFile.close
end if
oRs.MoveNext
oCn.Close
Loop
You ask for the CallID column;
"select CallID from dbo.CallLog"
but then try to read something else:
strfield = ors("Tracker")
so either select Tracker or read CallID.
You could also probably create/open the file outside of the loop.

Active Directory PSO fine grained passwords msDS-MaximumPasswordAge

Looking how to create a vbscript to pull the maximum number of days a PSO policy has set. It comes back as a value of ... and I do not know how to get the real value that was set.
This is what I have so far:
Option Explicit
Const ADS_UF_PASSWD_CANT_CHANGE = &H40
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000
Dim strFilePath, objFSO, objFile, adoConnection, adoCommand, objCDOConf
Dim objRootDSE, strDNSDomain, strFilter, strQuery, adoRecordset, objMaxPwdAge
Dim strDN, objShell, lngBiasKey, lngBias, blnPwdExpire, strDept, strAdd
Dim objDate, dtmPwdLastSet, lngFlag, k, address, objAdd, objMessage
' Check for required arguments.
If (Wscript.Arguments.Count < 1) Then
Wscript.Echo "Arguments <FileName> required. For example:" & vbCrLf _
& "cscript PwdLastChanged.vbs c:\MyFolder\UserList.txt"
Wscript.Quit(0)
End If
strFilePath = Wscript.Arguments(0)
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open the file for write access.
On Error Resume Next
Set objFile = objFSO.OpenTextFile(strFilePath, 2, True, 0)
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "File " & strFilePath & " cannot be opened"
Wscript.Quit(1)
End If
On Error GoTo 0
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
& "TimeZoneInformation\ActiveTimeBias")
If (UCase(TypeName(lngBiasKey)) = "LONG") Then
lngBias = lngBiasKey
ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
lngBias = 0
For k = 0 To UBound(lngBiasKey)
lngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If
' Use ADO to search the domain for all users.
Set adoConnection = CreateObject("ADODB.Connection")
Set adoCommand = CreateObject("ADODB.Command")
adoConnection.Provider = "ADsDSOOBject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
' Determine the DNS domain from the RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
' Filter to retrieve all user objects.
strFilter = "(&(objectClass=msDS-PasswordSettings))"
' Filter to retrieve all computer objects.
strQuery = "<LDAP://CN=PSO-Information Systems,CN=Password Settings Container,CN=System,DC=yrmc,DC=org>;" _
& ";cn,msDS-LockoutDuration,msDS-MaximumPasswordAge,msDS-
PasswordSettingsPrecedence;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
Do Until adoRecordset.EOF
objFile.WriteLine adoRecordset.Fields("cn").Value
adoRecordset.MoveNext
Loop
adoRecordset.Close
I can get a value for cn and even msDS-PasswordSettingsPrecedence but not for msDS-MaximumPasswordAge. Any help would be appreciated.
This is at best a partial answer but I did some searching and I believe you will need one or more of the following:
DSGet/DSQuery
LDIFDE to manage PSO's.
Quest's "Free PowerShell Commands for Active Directory"
Using Quest's free tools, you might find this link handy
Put square brackets around our Active Directory attribute name:
See the blog post "How can I retrieve the value of an active directory attribute that has a hyphen in its name" for more.
you have to find UsersPSO location in your AD like that
domainLookupString = ""CN=UsersPSO,CN=Password Settings Container,CN=System,DC=COMPAY,DC=ORG";
then run the ldap query
ldapFilterString = "(&(objectClass=msDS-PasswordSettings))";
at the end, get the ldap attribute with the Maximum Password Age of the current PSO policy
"msDS-MaximumPasswordAge"

Resources