Categories: Technical, VBscript Posted by jasond727 on 10/27/2010 8:16 AM | Comments (0)

So I had a task to get the members of a Exchange distribution list. What I ran into was lists members was another list and just kept going. So the solution I found was recursion.  This is the best way to go through a group and ensure that each itam is found.  Here is the code that I used to make that work.

On Error Resume Next

DLname = InputBox("Please enter Distribution List Name.")
GetMembership GetObject("LDAP://CN=" & DLname & ",OU=,OU=,dc=,dc=")
wscript.echo "Done!"

'Recursive Group member query
Sub GetMembership(objGroup)
On Error Resume Next
For Each objUser in objGroup.members
  GroupType = Split(objUser.objectCategory,",")

  If GroupType(0) = "CN=Group" Then
    GetMembership GetObject("LDAP://" & objUser.name & "," & "OU=,OU=,dc=,dc=")

    If Err.Number <> 0 Then
      wscript.echo objUser.name & ", " & objGroup.CN & " , " & Err.Number
      Err.Clear
    End If
  Elseif GroupType(0) = "CN=Person" Then
      wscript.echo objUser.mail & "," & objUser.title
  End If
Next
End Sub

So the most important thing is that initially calling the sub GetMembership and if the object is a group it recalls the sub again.  This allows it to go through every group and get the users for the current group and sub group.