Solved

vbs script to read list of users and export a file with the groups they belong to

Posted on 2012-03-29
7
510 Views
Last Modified: 2012-08-19
I would like to take a txt file that contains the list of multiple user accounts.  Then have it look at the domain and tell me what groups the user is in and export that info to a txt or csv file.  Below is an example but only allows you to enter one username and then gives you a text file with the groups that one user belongs to.  I need to remove that and allow it to read mulitple users.  


On Error Resume Next
Const ForWriting = 2

UserName = InputBox("Enter Username","Enter Username")

Set objUser = GetObject("LDAP://" & SearchDistinguishedName(UserName))
For Each strGroup in objUser.memberOf
        Set objGroup = GetObject("LDAP://" & strGroup)
        Report = Report & objGroup.CN & vbCrLf
Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile (UserName & "GroupMembership.txt", ForWriting)
ts.Write Report
WScript.Echo "Done"


Public Function SearchDistinguishedName(ByVal vSAN)
    ' Function:     SearchDistinguishedName
    ' Description:  Searches the DistinguishedName for a given SamAccountName
    ' Parameters:   ByVal vSAN - The SamAccountName to search
    ' Returns:      The DistinguishedName Name
    Dim oRootDSE, oConnection, oCommand, oRecordSet

    Set oRootDSE = GetObject("LDAP://rootDSE")
    Set oConnection = CreateObject("ADODB.Connection")
    oConnection.Open "Provider=ADsDSOObject;"
    Set oCommand = CreateObject("ADODB.Command")
    oCommand.ActiveConnection = oConnection
    oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _
        ">;(&(objectCategory=User)(samAccountName=" & vSAN & "));distinguishedName;subtree"
    Set oRecordSet = oCommand.Execute
    On Error Resume Next
    SearchDistinguishedName = oRecordSet.Fields("DistinguishedName")
    On Error GoTo 0
    oConnection.Close
    Set oRecordSet = Nothing
    Set oCommand = Nothing
    Set oConnection = Nothing
    Set oRootDSE = Nothing
End Function
0
Comment
Question by:zanderkid
  • 4
  • 3
7 Comments
 
LVL 65

Expert Comment

by:RobSampson
ID: 37785040
Hi, this should work.

Regards,

Rob,

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("Users_And_Their_Group_Memberships.csv", True)

'set connection to active directory      
Set adConnection = CreateObject("ADODB.Connection")
adConnection.Provider = "ADsDSOObject"
adConnection.Open("Ads Provider")
 
Set rsUsers = CreateObject("ADODB.Recordset")                                        
Set objRootDSE = GetObject("LDAP://RootDSE")
 
strFilter = "(&(objectCategory=user)(objectClass=person))"
strCmd = "<LDAP://" & objRootDSE.Get("defaultNamingContext") & ">;" & strFilter & ";adsPath;subtree"
 
'create recordset containing all active directory users
Set rsUsers = adConnection.Execute(strCmd)            
                 
While Not rsUsers.EOF
	Set objUser = GetObject(rsUsers.fields("adsPath"))
	If TypeName(objUser.MemberOf) = "Empty" Then
		strMemberOf = "<NONE>"
	ElseIf TypeName(objUser.MemberOf) = "String" Then
		strMemberOf = objUser.MemberOf
	ElseIf TypeName(objUser.MemberOf) = "Variant()" Then
		strMemberOf = Join(objUser.MemberOf, ";")
	End If
	objFile.WriteLine """" & objUser.samAccountName & """,""" & strMemberOf & """"
	rsUsers.MoveNext
Wend
rsUsers.Close
adConnection.Close

objFile.Close
Set objFile = Nothing
MsgBox "Done"

Open in new window

0
 

Author Comment

by:zanderkid
ID: 37785261
I think this is searching all the users in th entire domain.  I'm looking for the script to read a list of specific users. I ran this script and got the following:
The size limit for this request was exceeded.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 37785276
Oops.  Sorry...I missed the input file part.  Try this.

Regards,

Rob.

On Error Resume Next
Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")

Set objInput = fso.OpenTextFile("usernames.txt", ForReading, False)
Set objOutput = fso.CreateTextFile("GroupMemberships.txt", True)
While objInput.AtEndOfStream
	UserName = Trim(objInput.ReadLine)
	If UserName <> "" Then
		Set objUser = GetObject("LDAP://" & SearchDistinguishedName(UserName))
		strLine = objUser.samAccountName
		If TypeName(objUser.MemberOf) = "Empty" Then
			strLine = strLine & ",<<NONE>>"
		ElseIf TypeName(objUser.MemberOf) = "String" Then
			strLine = strLine & "," & objUser.MemberOf
		Else
			For Each strGroup in objUser.memberOf
				strLine = strLine & "," & strGroup
			Next 
		End If
		objOutput.WriteLine strLine
	End If
Wend
objInput.Close
objOutput.Close

WScript.Echo "Done"


Public Function SearchDistinguishedName(ByVal vSAN)
    ' Function:     SearchDistinguishedName
    ' Description:  Searches the DistinguishedName for a given SamAccountName
    ' Parameters:   ByVal vSAN - The SamAccountName to search
    ' Returns:      The DistinguishedName Name
    Dim oRootDSE, oConnection, oCommand, oRecordSet

    Set oRootDSE = GetObject("LDAP://rootDSE")
    Set oConnection = CreateObject("ADODB.Connection")
    oConnection.Open "Provider=ADsDSOObject;"
    Set oCommand = CreateObject("ADODB.Command")
    oCommand.ActiveConnection = oConnection
    oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _
        ">;(&(objectCategory=User)(samAccountName=" & vSAN & "));distinguishedName;subtree"
    Set oRecordSet = oCommand.Execute
    On Error Resume Next
    SearchDistinguishedName = oRecordSet.Fields("DistinguishedName")
    On Error GoTo 0
    oConnection.Close
    Set oRecordSet = Nothing
    Set oCommand = Nothing
    Set oConnection = Nothing
    Set oRootDSE = Nothing
End Function

Open in new window

0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 

Author Comment

by:zanderkid
ID: 37789092
The Last code posted does complete without error however it does not have any data.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 37790596
Can you comment out the On Error Resume Next line and run it again? Maybe you're getting an error you can't see.

Regards,

Rob.
0
 

Author Comment

by:zanderkid
ID: 37805817
I comment ou the On Error Resume next and the script still completed without error but no data in the output file
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 37809100
Oh I see what the problem is.  Change this line:
While objInput.AtEndOfStream

to this
While Not objInput.AtEndOfStream


Rob.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

This is pretty cool.  The purpose of this VB Script is to help you document where JAR (Java ARchive) files and specifically java class files are located so that you can address issues seen with a client or that you can speak intelligently with a dev…
Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

777 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