Wednesday, December 3, 2014

VB Script to list user from multiple group AD


'Populate Group details in Excel file (Vertical)
'-------------------------------------------------------

Option Explicit

Dim objConnection, objCommand, objRecordSet, objGroup, objRootDSE,objFile, objFileSystem, objMember
Dim strLine

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("c:\temp\Groups-03Dec2014.xls", 2, True, 0)
objFile.WriteLine "Group Name" & VbTab & "Number of Members" & VbTab & "Members"


Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT name, samaccountname, aDSPath,mail " &_
      "FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") & "' WHERE objectClass='group'"
Set objRootDSE = Nothing

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

wscript.echo "Started...!!!"

While Not objRecordSet.EOF
      Set objGroup = GetObject(objRecordSet.Fields("aDSPath"))
     
            strLine = objRecordSet.Fields("name") & VbTab
           
            strLine = strLine & objGroup.Members.Count & VbTab
           

            For Each objMember in objGroup.Members
                  strLine = strLine & objMember.Get("name") & "[" & objMember.Get("samaccountname") & "]" & ","
            Next

            If Right(strLine, 1) = "," Then
                  strLine = Left(strLine, Len(strLine) - 1)
            End If
            objFile.WriteLine strLine
     
      Set objGroup = Nothing
      objRecordSet.MoveNext
Wend

objConnection.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing

Set objFile = Nothing
Set objFileSystem = Nothing

wscript.echo "Completed...!!!"