Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to retrieve account attributes from AD

Status
Not open for further replies.

BDakis

MIS
Nov 26, 2003
12
US
I am working on a script that will retrieve specific user attributes from AD. The attributes I am looking for are:

sAMAccountName
userPrincipalName
distinguishedName
mail
legacyExchangeDN
proxyAddresses

I have a script that will return the sAMAccountName and userPrincipleName, but I can't get the other ones to retrieve. As well, the script I have is only hitting the Users container and I need to traverse the entire domain. Code I am workign with is below:


'==========================================================================
'
' VBScript Source File
'
' NAME: AD_User_Attribute_Query.vbs
'
' AUTHOR: Bill Dakis
' DATE : 03/21/2007
'
' COMMENT:
'
'==========================================================================
On Error Resume Next

Dim objDropDownList
Dim arrayDCs

Const TristateFalse = 0
Const ForAppending = 8

' Define Domain - This needs to be defined for each individual use!!
strDomain = "DC=Globalbank,DC=com"


' List DCs in a dropdown window
Call ListDCs()
arrayDCs = SortArray(arrayDCs,1)
arrayDropDown = arrayDCs
Set objDropDownList = New DropDownList
Do
strSelection = objDropDownList.SelectionMade
strConfirmation = MsgBox(strSelection & " has been selected. Is this correct?",vbQuestion + vbYesNo,"Confirm Domain Controller Selection")
If strConfirmation = vbYes Then
Exit Do
End If
Loop
strTargetDC = strSelection

'Edit the below line (component in quotes only) with the appropriate FQDN
strTargetDC = strTargetDC & ".Globalbank.COM"
Set objDropDownList = Nothing

'Create output file
Set objFSO = CreateObject("Scripting.FileSystemObject")
strTimeStamp = Right("0" & Month(Now),2) & "-" & Right("0" & Day(Now),2) & "-" & Year(Now) & "@" & Right("0" & Hour(Now),2) & Right("0" & Minute(Now),2) & Right("0" & Second(Now),2)
strOutputFile = "AD_User_Attribute_Query_Output_" & strTimeStamp & ".txt"
Set objOutput = objFSO.CreateTextFile(strOutputFile,true,TristateFalse)
With objOutput
.WriteLine "samAccountName|userPrincipalName|distinguishedName|mail|legacyExchangeDN|proxyAddresses|"
.Close
End With


' Use ADO to search Active Directory.
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
strBase = "<LDAP://" & strTargetDC & "/" & strDomain & ">"
strFilter = "(&(objectCategory=person)(objectClass=user))"
strAttributes = "sAMAccountName,userPrincipalName,distinguishedName" & _
",mail,legacyExchangeDN,proxyAddresses"

strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 200
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute

Do Until objRecordSet.EOF
strSAM = objRecordSet.Fields("sAMAccountName")
' strSur = objRecordSet.Fields("sn")
' strGiven = objRecordset.Fields("givenName")
' strIni = objRecordset.Fields("initials")
' strCN = objRecordset.Fields("cn")
strUPN = objRecordSet.Fields("userPrincipalName")
' strDisplay = objRecordSet.Fields("displayName")
strDN = objRecordSet.Fields("distinguishedName")
' strADSPath = objRecordSet.Fields("ADsPath")
strMail = objRecordSet.Fields("mail")
' strWC = objRecordSet.Fields("whenCreated")
strLegDN = objRecordSet.Fields("legacyExchangeDN")
strproxyAddrs = objRecordSet.Fields("proxyAddresses")

' strLastLogon = objRecordSet.Fields("lastLogonTimestamp")
' strLastLogon = Integer8Date(strLastLogon)

' strPWDLastSet = objRecordSet.Fields("pwdLastSet")
' strPWDLastSet = Integer8Date(strPWDLastSet)
' If strPWDLastSet = "1/1/1601" Then
' strPWDLastSet = "User must change password at next logon"
' End If

strHomeMDB = objRecordSet.Fields("homeMDB")

arrDescription = objRecordSet.Fields("description")
If IsNull(arrDescription) Then
strDescription = ""
Else
For Each strDescrip In arrDescription
strDescription = strDescrip
Next
End If

' strOffice = objRecordSet.Fields("physicalDeliveryOfficeName")
' strTelephoneNumber = objRecordSet.Fields("telephoneNumber")

' strStreetAddress = objRecordSet.Fields("streetAddress")
' If IsNull(strStreetAddress) Then
' strStreetAddress = ""
' Else
' strStreetAddress = Replace(Replace(strStreetAddress, Chr(13), "<cr>"),Chr(10),"<lf>")
' End If

' arrPostOfficeBox = objRecordSet.Fields("postOfficeBox")
' If IsNull(arrPostOfficeBox) Then
' strPostOfficeBox = ""
' Else
' For Each strPOBox In arrPostOfficeBox
' strPostOfficeBox = strPOBox
' Next
' End If

' strCity = objRecordSet.Fields("l")
' strState = objRecordSet.Fields("st")
' strPostalCode = objRecordSet.Fields("postalCode")
' strCountry = objRecordSet.Fields("c")
' strUserAccountControl = objRecordSet.Fields("userAccountControl")

' strAccountExpires = objRecordSet.Fields("accountExpires")
' strAccountExpires = Integer8Date(strAccountExpires)
' If strAccountExpires = "1/1/1601" Then
' strAccountExpires = "User account not set to expire"
' End If

' strProfilePath = objRecordSet.Fields("profilePath")
' strScriptPath = objRecordSet.Fields("scriptPath")
' strHomeDrive = objRecordSet.Fields("homeDrive")
' strHomeDirectory = objRecordSet.Fields("homeDirectory")
' strHomePhone = objRecordSet.Fields("homePhone")
' strPager = objRecordSet.Fields("pager")
' strMobile = objRecordSet.Fields("mobile")
' strFax = objRecordSet.Fields("facsimileTelephoneNumber")
' strIPPhone = objRecordSet.Fields("ipPhone")

' strInfo = objRecordSet.Fields("info")
' If IsNull(strInfo) Then
' strInfo = ""
' Else
' strInfo = Replace(Replace(strInfo, Chr(13), "<cr>"),Chr(10),"<lf>")
' End If

' strTitle = objRecordSet.Fields("title")
' strDepart = objRecordSet.Fields("department")
' strCompany = objRecordSet.Fields("company")
' strManager = objRecordSet.Fields("manager")

' wscript.echo "strSAM = " & strSAM
' wscript.echo "strSur = " & strSur
' wscript.echo "strGiven = " & strGiven
' wscript.echo "strIni = " & strIni
' wscript.echo "strCN = " & strCN
' wscript.echo "strUPN = " & strUPN
' wscript.echo "strDisplay = " & strDisplay
' wscript.echo "strDN = " & strDN
' wscript.echo "strADSPath = " & strADSPath
' wscript.echo "strMail = " & strMail
' wscript.echo "strWC = " & strWC
' wscript.echo "strLastLogon = " & strLastLogon
' wscript.echo "strLastLogon = " & strLastLogon
' wscript.echo "strPWDLastSet = " & strPWDLastSet
' wscript.echo "strHomeMDB = " & strHomeMDB
' wscript.echo "strDescription = " & strDescription
' wscript.echo "strOffice = " & strOffice
' wscript.echo "strTelephoneNumber = " & strTelephoneNumber
' wscript.echo "strStreetAddress = " & strStreetAddress
' wscript.echo "strPostOfficeBox = " & strPostOfficeBox
' WScript.echo "strCity = " & strCity
' wscript.echo "strState = " & strState
' WScript.echo "strPostalCode = " & strPostalCode
' wscript.echo "strCountry = " & strCountry
' WScript.echo "strUserAccountControl = " & strUserAccountControl
' wscript.echo "strAccountExpires = " & strAccountExpires
' wscript.echo "strProfilePath = " & strProfilePath
' wscript.echo "strScriptPath = " & strScriptPath
' wscript.echo "strHomeDrive = " & strHomeDrive
' wscript.echo "strHomeDirectory = " & strHomeDirectory
' wscript.echo "strHomePhone = " & strHomePhone
' wscript.echo "strPager = " & strPager
' wscript.echo "strMobile = " & strMobile
' wscript.echo "strFax = " & strFax
' wscript.echo "strIPPhone = " & strIPPhone
' wscript.echo "strInfo = " & strInfo
' wscript.echo "strTitle = " & strTitle
' WScript.echo "strDepart = " & strDepart
' WScript.echo "strCompany = " & strCompany
' WScript.echo "strManager = " & strManager

Set objOutputappend = objFSO.OpenTextFile(strOutputFile,ForAppending,False,TristateFalse)
With objOutputappend
.WriteLine strSAM & "|" & strUPN & "|" & strDN & "|" & strMail & "|" & strLegDN & "|" & strproxyAddrs
.Close
End With
objRecordSet.MoveNext
Loop
MsgBox "The AD_User_Attribute_Query script has completed." & VbCrLf & "Query results can be found in the AD_User_Attribute_Query output text file.",vbInformation,"Query Completed"


'=========================================================================
' CLASSES, FUNCTIONS & SUBS
'=========================================================================
'=========================================================================
' Function: Integer8Date This function converts Integer8 (64-bit) value
' known as FILETIME (a count of 100 nanosecond intervals since
' January 01, 1601 00:00:00 UTC)to a date/time in coordinated universal Time
' (UTC) format, formerly known as Greenwich mean time (GMT).
' This function does not compensate for local time.
'=========================================================================
Function Integer8Date(objDate)
On Error Resume Next
Dim lngDate, lngHigh, lngLow
If isNull(objDate) Then
Integer8Date = "Never"
Else
lngHigh = objDate.HighPart
lngLow = objdate.LowPart
' Account for error in IADslargeInteger property methods.
If lngLow < 0 Then
lngHigh = lngHigh + 1
End If
lngDate = #1/1/1601# + (((lngHigh * (2 ^ 32))+ lngLow) / 600000000) / 1440
' Trap error if lngDate is ridiculously huge.
On Error Resume Next
Integer8Date = CDate(lngDate)
If Err.Number <> 0 Then
On Error GoTo 0
Integer8Date = #1/1/1601#
End If
On Error GoTo 0
End If
End Function

'=========================================================================
' Function: ListDCs
'=========================================================================
Function ListDCs()
count = ""
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider;"
objCommand.ActiveConnection = objConnection

'Line below needs to be edited for specific AD!!!

strBase = "<LDAP://ou=Domain Controllers,dc=Globalbank,dc=com>"
strAttributes = "cn"
strFilter = "(&(objectCategory=computer))"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
Do Until objRecordSet.EOF
strDCName = objRecordSet.Fields("cn")
If count = "" Then
count = 0
ReDim arrayDCs(count)
Else
count = count + 1
ReDim Preserve arrayDCs(count)
End If
arrayDCs(count) = strDCName
objRecordSet.MoveNext
Loop
End Function


'=========================================================================
' Function: SortArray SortArray(arrayUnSorted,intAscending)
' ****This will work for words And numbers:
' arrayUnSorted = array to be sorted
' intAscending = ascending sorted (1) or descending sorting (any other character)
'=========================================================================
Function SortArray(arrayUnSorted,intAscending)
Dim intTempStore
Dim i, j
For i = 0 To UBound(arrayUnSorted) - 1
For j = i To UBound(arrayUnSorted)
If intAscending = 1 Then 'Sort Ascending
If arrayUnSorted(i) > arrayUnSorted(j) Then
intTempStore = arrayUnSorted(i)
arrayUnSorted(i) = arrayUnSorted(j)
arrayUnSorted(j) = intTempStore
End If
Else 'Sort Descending
If arrayUnSorted(i) < arrayUnSorted(j) Then
intTempStore = arrayUnSorted(i)
arrayUnSorted(i) = arrayUnSorted(j)
arrayUnSorted(j) = intTempStore
End If
End If
Next
Next
SortArray = arrayUnSorted
End Function

'=========================================================================
' Class: DropDownList
'=========================================================================
Class DropDownList
Private objFSO
' The FileSystemObject is needed to create DropDownList.html.
Private Sub Class_Initialize()
Set objFSO = CreateObject("Scripting.FileSystemObject")
End Sub

Private Sub Class_Terminate()
Set objFSO = Nothing
End Sub

Public Function SelectionMade()
SelectionMade = GetSelection()
End Function

Private Function GetSelection()
On Error Resume Next
Dim Ftemp, objHTML, IE, strPath, strStatus, intDataArraysize

' This block creates DropDownList.html in the temp folder.
Ftemp = objFSO.GetSpecialFolder(2)
Ftemp = Ftemp & "\DropDownList.html"
Set objHTML = objFSO.CreateTextFile(Ftemp, True)

' This block writes HTML code to DropDownList.html.
objHTML.WriteLine "<HTML><HEAD><TITLE>Select A Target DC</TITLE></HEAD>"
objHTML.WriteLine "<BODY BGCOLOR=" & Chr(34) & "#FF9900" & Chr(34) & " TEXT=" & Chr(34) & "black" & Chr(34) & ">"
objHTML.WriteLine "<SCRIPT LANGUAGE=" & Chr(34) & "VBSCRIPT" & Chr(34) & ">"
objHTML.WriteLine "Sub hiddenSelection_OnChange()"
objHTML.WriteLine "strSelection = document.DropDownForm.DropDownList.selectedIndex"
objHTML.WriteLine "document.DropDownForm.Selection.Value = strSelection"
objHTML.WriteLine "End Sub"
objHTML.WriteLine "Sub hiddenSubmit_OnClick()"
objHTML.WriteLine "strSelection = document.DropDownForm.Selection.Value"
objHTML.WriteLine "If strSelection = " & Chr(34) & "" & Chr(34) & " Or strSelection = " & Chr(34) & "0" & Chr(34) & " Then"
objHTML.Writeline "'Do Nothing"
objHTML.Writeline "Else"
objHTML.WriteLine "strSubmit=" & Chr(34) & "SUBMITTED" & Chr(34)
objHTML.WriteLine "document.DropDownForm.Submit.Value=strSubmit"
objHTML.WriteLine "End If"
objHTML.WriteLine "End Sub"
objHTML.WriteLine "</SCRIPT>"
objHTML.WriteLine "<DIV ALIGN=" & Chr(34) & "center" & Chr(34) & ">"
objHTML.WriteLine "<FONT FACE=" & Chr(34) & "arial" & Chr(34) & " SIZE=2>"
objHTML.WriteLine "<B>Make a selection:</B><BR>"
objHTML.WriteLine "<FORM NAME= " & Chr(34) & "DropDownForm" & Chr(34) & ">"
objHTML.WriteLine "<select name=" & Chr(34) & "DropDownList" & Chr(34) & " OnChange =" & Chr(34) & "hiddenSelection_OnChange()" & Chr(34) & ">"
objHTML.WriteLine "<option value=" & Chr(34) & Chr(34)& "selected>Choose...</option>"
For Each elem In arrayDropDown
objHTML.WriteLine "<option value=" & Chr(34) & Chr(34)& ">" & elem & "</option>"
Next
objHTML.WriteLine "</select>"
objHTML.WriteLine "<INPUT TYPE=Hidden Name=" & Chr(34) & "Selection" & Chr(34) & ">"
objHTML.WriteLine "<INPUT TYPE=Hidden Name=" & Chr(34) & "Submit" & Chr(34) & ">"
objHTML.WriteLine "<INPUT TYPE=Button OnClick=" & Chr(34) & "hiddenSubmit_OnClick()" & Chr(34) & " VALUE=" & Chr(34) & "Submit" & Chr(34) & ">"
objHTML.WriteLine "</FORM>"
objHTML.WriteLine "</FONT></DIV>"
objHTML.WriteLine "</BODY></HTML>"
objHTML.Close
Set objHTML = Nothing

' This block launches IE to open DropDownList.html.
Set IE = WScript.CreateObject("InternetExplorer.Application")
IE.Navigate "file:///" & Ftemp
IE.AddressBar = False
IE.MenuBar = False
IE.ToolBar = False
IE.StatusBar = False
IE.Width = 400
IE.Height = 150
IE.Resizable = False
IE.Visible = True

' This DO will Loop every 1/2 second until either:
' A selection is made and submitted
' or
' IE is closed from the control box
Do While IE.visible = True
' This line retrieves the hidden input values of DropDownList.html.
strSubmit = IE.document.DropDownForm.Submit.Value
strSelection = IE.document.DropDownForm.Selection.Value
If strSubmit = "SUBMITTED" Then
Exit Do
End If
If IE.Visible = False Then
MsgBox "Dropdown window closed and no selection made. Script Terminated!",vbCritical,"Error"
WScript.quit
End If
WScript.Sleep 500
Loop
IE.Visible = False
IE.Quit
Set IE = Nothing
strSelection = strSelection - 1
GetSelection = arrayDropDown(strSelection)
End Function
End Class
 
I don't have a VBscript on hand nor the time to go through your code currently, sorry... What I do have is an ldifde query that will return the attributes you are looking for.
You will need to run this at the command prompt on one of your domain controllers. This will create a text file called UserAttribs.txt with the information you are requesting.
Code:
ldifde -f UserAttribs.txt -d "dc=domainname.dc=com" -p subtree -r "(&(objectCategory=person)(objectClass=user)(givenname=*))" -l "objectClass,samAccountName,userPrincipalName,distinguishedName,mail,legacyExchangeDN,proxyAddresses"

you have to add the objectClass as it is a manditory attribute like samAccountName.

Microsoft link to LDIFDE info:
 
I actually dug up some other (more concise) code that I was able to manipulate and derive what I am loooking for. I am going to hold on to your ldifde piece though. Thanks!
 
Wow, you posted a TON of code. I see that much of it is commented out. I may recommend not posting that in places where you ask for help. This is so long that most may not answer.

Anyway, with so many times of code and since I do not know what you are trying to do with some of it, I am going to address your questions only. I will post a script below that will return the values you want from any user account in the domain.

Code:
Option Explicit

Dim objRootDSE, strDNSDomain, objCommand, objConnection
Dim strQuery, strBase, strFilter, strAttributes
Dim objRecordSet, strDN, strSAM, address
Dim strUPN, strMAIL, strEXDN, strPROX
Dim objUser, strValue

' Determine DNS domain name from RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Use ADO to search Active Directory.
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection

' Search for all user objects. Return Values.
strBase = "<LDAP://" & strDNSDomain & ">"
strFilter = "(&(objectCategory=person)(objectClass=user))"
strAttributes = "userPrincipalName,mail,sAMAccountName,distinguishedName,legacyExchangeDN,proxyAddresses"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
objCommand.Properties("Sort On") = "displayName"
Set objRecordSet = objCommand.Execute
  
    Do Until objRecordSet.EOF
  strDN = objRecordSet.Fields("distinguishedName")
  strUPN = objRecordSet.Fields("userPrincipalName")
  strMAIL = objRecordSet.Fields("mail")
  strEXDN = objRecordSet.Fields("legacyExchangeDN")
  strSAM = objRecordSet.Fields("sAMAccountName")
  strPROX = objRecordSet.Fields("proxyAddresses")
  
  If Not IsNull(strPROX) Then
  strPROX = Join(strPROX)
  End If

  Wscript.Echo "DN: " & strDN & vbcrlf & "UPN: " & strUPN & vbcrlf _
  & "Mail: " & strMAIL & vbcrlf & "EXDN: " & strEXDN & vbcrlf & "SAM: " &_
  strSAM & vbcrlf & "PROX: " & strPROX & vbcrlf & vbcrlf
  	
    objRecordSet.MoveNext
	Loop

objConnection.Close
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top