Pages

Monday, September 17, 2012

Script to pull group membership or users in DL

 Below is the script that will generate the output in text file. You need to save the file as .vbs and run (either from command prompt or directly). If you want to run .vbs script from command then use the command :
c:\csript example.vbs

Note: Below is the script that should be run after testing in test environment. Do not run directly on production without testing. Run the script at your own risk.
============================

' Set up the output file
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFile : Set objFile = objFSO.OpenTextFile("Output.csv", 2, True, 0)

objFile.WriteLine "Group Name,Members,Addresses"

' Find and connect to the current domain
Dim objRootDSE : Set objRootDSE = GetObject("LDAP://RootDSE")
Dim strSearchRoot : strSearchRoot = "LDAP://" & objRootDSE.Get("defaultNamingContext")

' Get a list of groups
Set objGroups = DirectorySearcher(strSearchRoot, _
  "(&(objectClass=group)(mail=*))", _
  "distinguishedName,name,proxyAddresses", _
  "subtree", _
  "distinguishedName")

' Find the members for each group
Dim arrUsers()
For Each strGroup in objGroups
  Set objMembers = DirectorySearcher(strSearchRoot, _
    "(&(memberOf=" & strGroup & "))", _
    "distinguishedName,name", _
    "subtree", _
    "distinguishedName")

  ReDim arrUsers(0)
  For Each strMember in objMembers
    arrUsers(UBound(arrUsers)) = objMembers(strMember)(1)

    ReDim Preserve arrUsers(UBound(arrUsers) + 1)
  Next

  ' Write output to the file
  objFile.WriteLine objGroups(strGroup)(1) & "," & Join(arrUsers, ";") & "," & objGroups(strGroup)(2)
Next


'
' Functions
'

Function DirectorySearcher(strLdapPath, strLdapFilter, strPropertiesToLoad, strScope, strKey)
  ' Returns a dictionary object containing search results. Key is object distinguished name.

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

  Dim objCommand : Set objCommand = Createobject("ADODB.Command")
  objCommand.ActiveConnection = objConnection
  objCommand.Properties("Page Size") = 1000

  objCommand.CommandText = "<" & strLdapPath & ">;" & _
    strLdapFilter & ";" & strPropertiesToLoad & ";" & strScope

  Dim objRecordSet : Set objRecordSet = objCommand.Execute

  Dim arrPropertiesToLoad : arrPropertiesToLoad = Split(strPropertiesToLoad, ",")

  Dim objSearchResults : Set objSearchResults = CreateObject("Scripting.Dictionary")
  objSearchResults.CompareMode = VbTextCompare

  Dim arrValues()
  Do Until objRecordSet.EOF
    Dim strProperty, strValue : Dim i : i = 0
    For Each strProperty in arrPropertiesToLoad
      If IsNull(objRecordSet.Fields(strProperty)) Then
        strValue = ""
      Else
        strValue = objRecordSet.Fields(strProperty).Value
        If IsArray(strValue) Then
          strValue = Join(strValue, ";")
        End If
      End If
      ReDim Preserve arrValues(i)
      arrValues(i) = strValue : i = i + 1
    Next

    objSearchResults.Add objRecordSet.Fields(strKey).Value, arrValues

    objRecordSet.MoveNext
  Loop

  Set DirectorySearcher = objSearchResults
End Function
================================


Thanks Chris dent for the script.


The above script will generate the output in text format later which can be imported to excel and do the necessary format to get the desired look. If you want the output to be in HTML format then below is the perfect script. Just copy the below script and save it as .vbs and run:

================================
' This script is designed to be run at a command prompt, using the
' Cscript host. The output can be redirected to a text file.
' For example:
' cscript //nologo DocumentGroups.vbs > groups.txt
'
' You have a royalty-free right to use, modify, reproduce, and
' distribute this script file in any way you find useful, provided that
' you agree that the copyright owner above has no warranty,obligations,
' or liability for such use.

Option Explicit


Dim objConnection, objCommand, objRootDSE, strDNSDomain, strQuery

Dim objRecordSet, strDN, objGroup
Dim FileSystem, oFile
' Open Text File for Output
Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set oFile = FileSystem.CreateTextFile("GroupMemebrshipNew.html", True)

oFile.writeLine "<HTML><HEAD><TITLE>Group Membership for MyDomain.com</TITLE><HEAD><BODY>"

oFile.writeLine "<h4><TABLE width=100% border=0 padding=0 cellspacing=0 valign=top>"


' Use ADO to search Active Directory.

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

' Determine the DNS domain from the RootDSE object.

Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Search for all groups, return the Distinguished Name of each.

strQuery = "<LDAP://" & strDNSDomain _
& ">;(objectClass=group);distinguishedName;subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False

Set objRecordSet = objCommand.Execute

If objRecordSet.EOF Then
Wscript.Echo "No groups found"
objConnection.Close
Set objRootDSE = Nothing
Set objConnection = Nothing
Set objCommand = Nothing
Set objRecordSet = Nothing
Wscript.Quit
End If

' Enumerate all groups, bind to each, and document group members.

Do Until objRecordSet.EOF
strDN = objRecordSet.Fields("distinguishedName")
Set objGroup = GetObject("LDAP://" & strDN)

' OUTPUT

oFile.writeLine "<TR>"
oFile.writeLine "<TD width=20% valign=top bgcolor=black><font color=white><strong><u>" & "Group Name:" &_
"</u></strong></font></TD><TD width=80% valign=top><strong>" &_
objGroup.SAMaccountName & "</strong></TD>"
oFile.writeLine "</TR><TR>"
oFile.writeLine "<TD valign=top bgcolor=black><font color=white><strong><u>" & "Distinguished Name:" &_
"</u></strong></font></TD><TD valign=top><strong>" &_
objGroup.distinguishedName & "</strong></TD>"
oFile.writeLine "</TR><TR>"
oFile.writeLine "<TD valign=top bgcolor=black><font color=white><strong><u>" & "Description:" &_
"</u></strong></font></TD><TD valign=top><strong>" &_
objGroup.description & "</strong></TD>"
oFile.writeLine "</TR><TR>"
oFile.writeLine "<TD valign=top bgcolor=black><font color=white><strong><u>" & "Type:" & "</u></strong></font></TD><TD valign=top><strong>" & GetType(objGroup.groupType) & "</strong></TD>"
oFile.writeLine "</TR>"

oFile.writeLine "<TR><TD valign=top bgcolor=black><font color=white><strong><u>Members:</font></TD><TD align=left valign=top>"

oFile.writeLine "<TABLE width=70% border=0 cellspacing=0 cellpadding=0>"
oFile.writeLine "<Tr>"
oFile.writeLine " <TD valign=top><strong><u> Name </u></strong></TD>"
oFile.writeLine " <TD valign=top><strong><u> Account </u></strong></TD>"
oFile.writeLine " <TD valign=top><strong><u> Type </u></strong></TD>"
oFile.writeLine "</Tr>"
Call GetMembers(objGroup)
oFile.writeLine "</TABLE>"

oFile.writeLine "</TD></TR>"


oFile.writeLine "<TR><TD COLSPAN=2><hr width=90%></TD></TR>"



objRecordSet.MoveNext


Loop

oFile.writeLine "</TABLE></BODY></HTML>"

msgBox "Done !!!"


' Clean up.

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

Function GetType(intType)

' Function to determine group type from the GroupType attribute.
If (intType And &h01) <> 0 Then
GetType = "Built-in"
ElseIf (intType And &h02) <> 0 Then
GetType = "Global"
ElseIf (intType And &h04) <> 0 Then
GetType = "Local"
ElseIf (intType And &h08) <> 0 Then
GetType = "Universal"
End If
If (intType And &h80000000) <> 0 Then
GetType = GetType & "/Security"
Else
GetType = GetType & "/Distribution"
End If
End Function

Sub GetMembers(objADObject)

' Subroutine to document group membership.
' Members can be users or groups.
Dim objMember, strType
For Each objMember In objADObject.Members
If UCase(Left(objMember.objectCategory, 8)) = "CN=GROUP" Then
strType = "Group"
Else
strType = "User"
End If

' OUTPUT


oFile.writeLine "<TR>"

oFile.writeLine "<TD valign=top>" & objMember.displayName & _
"</TD><TD valign=top>" & objMember.SAMaccountName & _
"</TD><TD valign=top>" & strType & "</TD>"
oFile.writeLine "</TR>"
' Wscript.Echo " Member: " & objMember.sAMAccountName & " (" & strType & ")"
Next
Set objMember = Nothing
End Sub 

================================

 I have tested the above script on Windows 2008 and it worked like a charm.. awesome script .











                                             

1 comment:

  1. Hello Bro,

    Excellent script, i am able to get the group membership or users in DL.

    Thanks,
    Puli.

    ReplyDelete