Put DN into variable VBS - vbscript

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

Related

How to return a XMLDom object forom classic asp function [duplicate]

I am loosing my hair on VBScript. How the heck can I pass a reference as return value of a function?
Currently my code looks like this:
Set objUser = FindUser("bendert")
REM Searches Directory for the User
Function FindUser(UserLoginName)
Wscript.Echo "Querying AD to retrieve user-data"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
'Get user Using LDAP/ADO. There is an easier way
'to bind to a user object using the WinNT provider,
'but this way is a better for educational purposes
Set oRoot = GetObject("LDAP://rootDSE")
'work in the default domain
sDomain = oRoot.Get("defaultNamingContext")
Set oDomain = GetObject("LDAP://" & sDomain)
sBase = "<" & oDomain.ADsPath & ">"
'Only get data for login name requested
sFilter = "(&(sAMAccountName="& UserLoginName &")(objectClass=user))"
sAttribs = "adsPath"
sDepth = "subTree"
sQuery = sBase & ";" & sFilter & ";" & sAttribs & ";" & sDepth
WScript.Echo "LDAP Query is:" & sQuery &""
objCommand.CommandText=sQuery
Set objRecordSet = objCommand.Execute
FindUser = GetObject(objRecordSet.Fields("adspath"))
WScript.Echo "You E-Mail Address is: " & objUser.EmailAddress
objConnection.Close
End Function
Unfortunatley VBScript throws an error on the line where I make an assignment to the function's return value.
FindUser = GetObject(objRecordSet.Fields("adspath"))
The Error looks like "wrong number of arguments or invalid property assignment".
What am I doing wrong?
Looks like you need:
Set FindUser = GetObject(objRecordSet.Fields("adspath"))
Set FindUser = ...
http://msdn.microsoft.com/en-us/library/4afksd44%28VS.85%29.aspx

VBScript \ Active Directory Searched by displayname and received 2 of the same

I have my script to search by displayname and return the userid, which works fine.
but when I encounter a displayname that has 2 entries in AD i.e.
pavle stojanovic - he is from company 1
pavle stojanovic - he is from company 2
the userid doesnt get displayed because the script doesnt know what to do ?
how do i over come this ? if I get a return of 2 or more I'd like to say in the output hey i found the same name twice etc.. here are the userids and companies for both.
If you want to see the script its below...
strFile = objFSO.GetParentFolderName(Wscript.ScriptFullName) & "\users.xls"
Set objWorkbook = objExcel.Workbooks.Open(strFile)
objWorkbook.Activate
objExcel.Visible = False
intRow = 2 ' starts reading file at line 2
' this part runs a loop through the excel file reading each userid and getting data requested.
' ---------------------------------------------------------------------------------------------
Do Until objExcel.Cells(intRow,1).Value = ""
ExcelRow = objExcel.Cells(intRow, 1)
Call GetOU ' calling sub to search
intRow = intRow + 1
Loop
' This section just formats the excel file to widen the columns
' --------------------------------------------------------------
Set objRange = objExcel.Range("A1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("B1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("C1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("D1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
objExcel.ActiveWorkbook.Save
objExcel.Quit
' Sub to get Details for user
' ----------------------------
Sub GetOU
On Error Resume Next
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand = CreateObject("ADODB.Command")
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Size Limit") = 100000
objCommand.Properties("Searchscope") = 2
objCommand.CommandText = "SELECT distinguishedName FROM 'LDAP://" & _
strDomain & _
"' WHERE objectCategory='User' AND DisplayName = '" & _
ExcelRow & "'"
Set objRecordSet = objCommand.Execute
If Not objRecordSet.EOF Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
' This is where the script does 'its thing' ...
' gets what you want.
' ------------------------------------------------
Set MyUser = GetObject ("LDAP://" & strDN)
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
' ###########################################################
' ###########################################################
Else
Wscript.Echo "User Not Found: " & ExcelRow
End If
Err.Clear
End Sub
If multiple accounts are found, the Record Set will have multiple records and you'll need to loop through it. Your code currently only gets the first item in the Record Set.
Change If Not objRecordSet.EOF Then to Do While Not objRecordSet.EOF
Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
Set MyUser = GetObject ("LDAP://" & strDN)
When inserting the users into the spreadsheet, you'll want to control the placement of the cell dynamically so the same cell isn't written over at each loop.
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
At the end of processing this user, you'll use this to move to the next object (user) in the Record Set
objRecordSet.MoveNext
Then instead of End If, you'll use Loop
EDIT:
Also, instead of connecting to the object using Set MyUser = GetObject(etc), could you just use "SELECT sAMAccountName FROM... in your query then strsAMAccountName = objRecordSet.Fields("sAMAccountName") to save some memory/time?
Edit2:
I am doing this in my script.
If objRecordSet.RecordCount = 0 Then
'Things to do if not found
Exit Sub 'Then exit before entering loop
End If
Also, if the user isn't found then objRecordSet.EOF will equal True.

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

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

Get SamAccountname using DisplayName in Active Directory

I need vbscript that will do an LDAP query using a displayname, and retrieve the SamAccountName for me.
Something like this should do it:
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Open "Provider=ADsDSOObject;"
objCommand.ActiveConnection = objConnection
strDomainName = "dc=YOURDOMAIN,dc=com"
strUserCN = "FIRSTNAME LASTNAME"
objCommand.CommandText = "<LDAP://" & strDomainName & ">;(&(objectCategory=person)(objectClass=user)(cn=" & strUserCN & "));samAccountName;subtree"
Set objRecordSet = objCommand.Execute
If Not objRecordset.EOF Then
WScript.Echo objRecordSet.Fields("samAccountName")
End If
objConnection.Close
Set objRecordSet = Nothing
Set objConnection = Nothing
Set objCommand = Nothing
Great script ( and thankyou ) but at the moment only shows the first result in the recordset - the displaying the output bit needs to something more like this:
DO until objRecordset.EOF = TRUE
WScript.Echo objRecordSet.Fields("samAccountName")
objRecordSet.MoveNext
Loop

Returning References from Function in VBScript

I am loosing my hair on VBScript. How the heck can I pass a reference as return value of a function?
Currently my code looks like this:
Set objUser = FindUser("bendert")
REM Searches Directory for the User
Function FindUser(UserLoginName)
Wscript.Echo "Querying AD to retrieve user-data"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
'Get user Using LDAP/ADO. There is an easier way
'to bind to a user object using the WinNT provider,
'but this way is a better for educational purposes
Set oRoot = GetObject("LDAP://rootDSE")
'work in the default domain
sDomain = oRoot.Get("defaultNamingContext")
Set oDomain = GetObject("LDAP://" & sDomain)
sBase = "<" & oDomain.ADsPath & ">"
'Only get data for login name requested
sFilter = "(&(sAMAccountName="& UserLoginName &")(objectClass=user))"
sAttribs = "adsPath"
sDepth = "subTree"
sQuery = sBase & ";" & sFilter & ";" & sAttribs & ";" & sDepth
WScript.Echo "LDAP Query is:" & sQuery &""
objCommand.CommandText=sQuery
Set objRecordSet = objCommand.Execute
FindUser = GetObject(objRecordSet.Fields("adspath"))
WScript.Echo "You E-Mail Address is: " & objUser.EmailAddress
objConnection.Close
End Function
Unfortunatley VBScript throws an error on the line where I make an assignment to the function's return value.
FindUser = GetObject(objRecordSet.Fields("adspath"))
The Error looks like "wrong number of arguments or invalid property assignment".
What am I doing wrong?
Looks like you need:
Set FindUser = GetObject(objRecordSet.Fields("adspath"))
Set FindUser = ...
http://msdn.microsoft.com/en-us/library/4afksd44%28VS.85%29.aspx

Resources