Solved

VBS script to list attributes of users in a txt file

Posted on 2011-09-16
3
453 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
ID: 36550735
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
ID: 36555982
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
ID: 36573842
Had to modify it to get what I needed but worked just fine. Thanks
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I met Paul Devereux (@pdevereux) today when I responded to his tweet asking “Anybody know how to automate adding files from disk to a folder in #outlook  ?”.  I replied back and told Paul that using automation, in this case scripting, to add files t…
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

730 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