Solved

VBS script to list attributes of users in a txt file

Posted on 2011-09-16
3
439 Views
Last Modified: 2012-08-14
I want to basically change the code below to read each user I have in a txt file example: c:\users.txt and get the attributes I specifty similar to the script below. which you enter a group name and it gives you all the users in that group and the specified attributes.  I don't want to enter a group name i just want these particular attributes for each user in my txt file.  

const FileName = "groupmembers.csv"

groupName = inputbox("Please enter the name of the group:")

if groupName = "" then
      wscript.quit
end if

groupPath = getgrouppath(groupName)

if groupPath = "" then
      wscript.echo "Unable to find the specified group in the domain"
      wscript.quit
end if

set objGroup = getobject(grouppath)
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.createtextfile(FileName)
q = """"


objFile.WriteLine(q & "distinguishedName" & q & "," & q & "sAMAccountName" & q & "," & q & "SN" & q & "," & q & "CN" & q & "," & q & "displayName" & q & "," & q & "userPrincipalName" & q & "," & q & "physicalDeliveryOfficeName" & q & "," & q & "homeDrive" & q & "," & q & "homeDirectory" & q & "," & q & "givenName" & q & "," & q & "Title" & q)
for each objMember in objGroup.Members
      objFile.WriteLine(q & objmember.distinguishedName & q & "," & q & objmember.samaccountname & q & "," & q & objmember.sn & q & "," & q & objmember.CN & q & "," & q & objmember.displayName & q & "," & q & objmember.userPrincipalName & q & "," & q & objmember.physicalDeliveryOfficeName & q & "," & q & ObjMember.homeDrive  & q & "," & q & ObjMember.homeDirectory & q & "," & q & objmember.givenName & q & "," & q & objmember.Title & q)
next

'***** Users who's primary group is set to the given group need to be enumerated seperatly.*****
getprimarygroupmembers groupname

objFile.Close

wscript.echo "Completed"

function getGroupPath(byval GroupName)
      set cmd=createobject("ADODB.Command")
      set cn=createobject("ADODB.Connection")
      set rs=createobject("ADODB.Recordset")
      
      cn.open "Provider=ADsDSOObject;"
      
      cmd.commandtext = "SELECT adspath from 'LDAP://" & getnc & _
                    "' WHERE objectCategory = 'Group' and sAMAccountName = '" & groupname & "'"
      cmd.activeconnection = cn
      
      set rs = cmd.execute
      
      if rs.bof <> true and rs.eof<>true then
            getgrouppath=rs(0)
      else
            getgrouppath = ""
      end if
      cn.close

end function

function getNC
      set objRoot=getobject("LDAP://RootDSE")
      getNC=objRoot.get("defaultNamingContext")
end function

function getPrimaryGroupMembers(byval GroupName)
      set cn = createobject("ADODB.Connection")
      set cmd = createobject("ADODB.Command")
      set rs = createobject("ADODB.Recordset")
      
      cn.open "Provider=ADsDSOObject;"
      cmd.activeconnection=cn

      '***** Change the Page Size to overcome the 1000 record limitation *****
      cmd.properties("page size")=1000
      cmd.commandtext = "SELECT PrimaryGroupToken FROM 'LDAP://" & getnc & _
                    "' WHERE sAMAccountName = '" & GroupName & "'"
      set rs = cmd.execute

      if rs.eof<>true and rs.bof<>true then
            PrimaryGroupID = rs(0)
      else
            Err.Raise 5000, "getPrimaryGroupMembers", "Unable to find PrimaryGroupToken property"
      end if

      cmd.commandtext = "SELECT samaccountname, sn, givenName FROM 'LDAP://" & getNC & _
                    "' WHERE PrimaryGroupID = '" & PrimaryGroupID & "'"

      set rs = cmd.execute

      while rs.eof<>true and rs.bof<>true
            objFile.WriteLine(q & rs("samaccountname") & q & "," & q & rs("sn") & q & _
                          "," & q & rs("givenName") & "," & q & rs("dn") & q)
            rs.movenext
      wend
      cn.close
      
end function
0
Comment
Question by:zanderkid
3 Comments
 
LVL 6

Expert Comment

by:effes
Comment Utility
Hi zanderkid,

I can't really help you with the code you posted but have a look at this
http://www.rlmueller.net/DocumentUsers.htm
and especially at the linked DocumentUsers.txt. It seems like it's doing what you want (I can't check that richt now). You will have to tweak it a bit to give you the attributes you want, but that shouldn't be too hard (look at the lines follwing "' Comma delimited list of attribute values to retrieve.").

Hope that helps,
Frank
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
Comment Utility
Hi, assuming you have the samaccountname in the text file of each user, one per line, try this script.

Regards,

Rob.
strInputFile = "users.txt"
strOutputFile = "userinfo.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Set objInput = objFSO.OpenTextFile(strInputFile, intForReading, False)
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine """distinguishedName"",""sAMAccountName"",""SN"",""CN"",""displayName"",""userPrincipalName"",""physicalDeliveryOfficeName"",""homeDrive"",""homeDirectory"",""givenName"",""Title"""
While Not objInput.AtEndOfStream
	strUsername = Trim(objInput.ReadLine)
	If strUsername <> "" Then
		strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adsPath")
		If Left(UCase(strUserADsPath), 7) = "LDAP://" Then
			Set objUser = GetObject(strUserADsPath)
			objOutput.WriteLine """" & objUser.distinguishedName & """," & _
				"""" & objUser.samAccountName & """," & _
				"""" & objUser.sn & """," & _
				"""" & objUser.cn & """," & _
				"""" & objUser.displayName & """," & _
				"""" & objUser.userPrincipalName & """," & _
				"""" & objUser.physicalDeliveryOfficeName & """," & _
				"""" & objUser.homeDrive & """," & _
				"""" & objUser.homeDirectory & """," & _
				"""" & objUser.givenName & """," & _
				"""" & objUser.Title & """"
		Else
			WScript.Echo "Unable to find account for " & strUserName
		End If
	End If
Next
objInput.Close
objOutput.Close

WScript.Echo "Finished"

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '             It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '             For example, if you are searching based on the user account name, strSearchField
      '             would be "samAccountName", and strObjectToGet would be that speicific account name,
      '             such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      ' strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '             the home folder path, as defined by the AD, for a specific user, this would be
      '             "homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '             user and get your own parameters from them, then use "ADsPath" as a return string,
      '             then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set ADOConnection = CreateObject("ADODB.Connection")
      ADOConnection.Provider = "ADsDSOObject"
      ADOConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = ADOConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & vbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      ADOConnection.Close
      Get_LDAP_User_Properties = strReturnVal
 
End Function

Open in new window

0
 

Author Closing Comment

by:zanderkid
Comment Utility
Had to modify it to get what I needed but worked just fine. Thanks
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

When it comes to writing scripts for a Client/Server computing environment it is essential to consider some way of enabling the authentication functionality within a script. This sort of consideration mainly comes into the picture when we are dealin…
Introduction During my participation as a VBScript contributor at Experts Exchange, one of the most common questions I come across is this: "I have a script that runs against only one computer. How can I make it run against a list of computers in …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now