Skip to main content

Counting the number and type of Members in a Distribution list / Group via a script

A couple of months back I posted this script that would detect any empty distribution groups and give you the chance to delete them. Another useful thing to do now and again when your examining distribution lists in your Exchange organization is to look at how many members each group has and also what type of objects are members of certain lists. In Exchange apart from just user mailboxes you may have contacts (both internal and external), nested groups, Query based distribution lists or even public folders that are members of a distribution list. So its possible that some lists may have collected unwanted baggage in the normal course of events.

So what I’ve done is come up with 3 different scripts for counting members based on the type of member of each distribution list and then generating a little html report to show the number of each type of object within each distribution list. The first script just does a basic count of the members of each list the second expands any nested groups so it comes up with the true number of members of a list (e.g. if you send a mail to this list how many mailboxes a mail will be delivered to etc). The third script is a script that looks at all the Query based distribution lists (where the first two look just at groups) and expands each list.

The script is broken up into a multitude of ADSI queries the first query that is done is for the purpose of calculating whether contacts that are enumerated by the script have a external or internal target address. To differentiated between internal and external all the domains that are listed in each of the recipient policies are enumerated and then added to a scripting dictionary. The dictionary can then be easily checked to see if the domain of the target email address for the contact is internal or external.

The next query then enumerates all groups that are mail enabled and goes through each group one at a time and looks though the members collection of each group looking at the email address and type of each member. Separate variables track the number of each of the type of objects and if the type of object is a group or dynamic distribution list then the group is expanded and each member of that group is also checked. To guard against circular references a separate scripting dictionary object is maintained to ensure that each object is checked and recorded only once per iteration. A separate sub exists to handle the expansion of query based distribution lists by reading the filter AD attributes and then doing a separate ADSI query baaed on these values. Finally there is some code that then builds the result into a html table to display to the users. The report is named Groupreport.htm and is stored in c:\temp directory.

I’ve put a downloadable copy of the three scripts here basically the three scripts contained in the download are

gnumbs.vbs Only counts member of the current list doesn’t process nested lists

gnumbsnested.vbs Counts all member of a groups including those in nested groups and Query based DL’s

gnumbsqbdl.vbs Displays total number of members for Querybased Distribution lists

the nested group script looks like

set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"

report = "<table border=""1"" width=""100%"">" & vbcrlf
report = report & " <tr>" & vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Group-Name</font></b></td>"
& vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Total
Number of Members</font></b></td>" & vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Mailboxes</font></b></td>"
& vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Contacts-Internal</font></b></td>"
& vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Contacts-External</font></b></td>"
& vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Groups</font></b></td>"
& vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">QueryBased
Dl's</font></b></td>" & vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">Public
Folders</font></b></td>" & vbcrlf
report = report & "<td align=""center"" bgcolor=""#000080""><b><font color=""#FFFFFF"">InterOrg-Person</font></b></td>"
& vbcrlf
report = report & "</tr>" & vbcrlf

trackCicularref = ""

numcheck = 0
usNumberUsers = 0
cnNumberinContacts = 0
cnNumberexContacts = 0
nsNumberGroups = 0
pfNumberPublicFolders = 0
ioNumberIorgPersons = 0
QbNumberQBDLs = 0
set trackmembers = CreateObject("Scripting.Dictionary")


GALQueryFilter = "(&(mail=*)(objectCategory=group))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter & ";distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
Com.ActiveConnection = Conn
Com.Properties("SearchScope") = 2 ' we want to search everything
Com.Properties("Page Size") = 500 ' and we want our records in lots of 500 (must
be < query limit)
polQuery = "<LDAP://" & iAdRootDSE.Get("configurationNamingContext") & ">;(objectCategory=msExchRecipientPolicy);distinguishedName,gatewayProxy;subtree"
Com.CommandText = polQuery
set sdSMTPDomains = CreateObject("Scripting.Dictionary")
Set adRs = Com.Execute
while not adRs.eof
for each adr in adRs.fields("gatewayproxy").value
if instr(lcase(adr),"smtp:") then
if sdSMTPDomains.exists(LCase(right(adr,(len(adr)-instr(adr,"@"))))) then
else
sdSMTPDomains.Add LCase(right(adr,(len(adr)-instr(adr,"@")))),1
end if
end if
next
adRs.movenext
Wend

Com.CommandText = strQuery
Set Rs = Com.Execute

while not rs.eof
trackmembers.RemoveAll
numcheck = 0
usNumberUsers = 0
cnNumberinContacts = 0
cnNumberexContacts = 0
nsNumberGroups = 0
pfNumberPublicFolders = 0
ioNumberIorgPersons = 0
QbNumberQBDLs = 0
trackmembers.add rs.fields("distinguishedName"),1
enumgroup(getobject("LDAP://" &
replace(rs.fields("distinguishedName"),"/","\/")))
wscript.echo rs.fields("displayname")
wscript.echo usNumberUsers
wscript.echo cnNumberinContacts
wscript.echo cnNumberexContacts
wscript.echo nsNumberGroups
wscript.echo QbNumberQBDLs
wscript.echo pfNumberPublicFolders
wscript.echo ioNumberIorgPersons
report = report & "<tr>" & vbcrlf
report = report & "<td align=""center"">" & rs.fields("displayname") &
"&nbsp;</td>" & vbcrlf
report = report & "<td align=""center"">" & numcheck & "&nbsp;</td>" & vbcrlf
report = report & "<td align=""center"">" & usNumberUsers & "&nbsp;</td>" &
vbcrlf
report = report & "<td align=""center"">" & cnNumberinContacts & "&nbsp;</td>" &
vbcrlf
report = report & "<td align=""center"">" & cnNumberexContacts & "&nbsp;</td>" &
vbcrlf
report = report & "<td align=""center"">" & nsNumberGroups & "&nbsp;</td>" &
vbcrlf
report = report & "<td align=""center"">" & QbNumberQBDLs & "&nbsp;</td>" &
vbcrlf
report = report & "<td align=""center"">" & pfNumberPublicFolders &
"&nbsp;</td>" & vbcrlf
report = report & "<td align=""center"">" & ioNumberIorgPersons & "&nbsp;</td>"
& vbcrlf
report = report & "</tr>" & vbcrlf
rs.movenext
wend

report = report & "</table>" & vbcrlf
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\temp\Groupreport.htm",2,true)
wfile.write report
wfile.close
set wfile = nothing
set fso = nothing

sub enumGroup(objgroup)
for each member in objgroup.members
if Not trackmembers.exists(member.distinguishedName) Then
trackmembers.add member.distinguishedName,1
wscript.echo member.class & " " & member.displayname
If member.mail <> "" then
Select Case member.Class
Case "user" usNumberUsers = usNumberUsers + 1
Case "contact" wscript.echo
right(member.mail,(len(member.mail)-instr(member.mail,"@")))
If
sdSMTPDomains.exists(LCase(right(member.mail,(len(member.mail)-instr(member.mail,"@")))))
Then
cnNumberinContacts = cnNumberinContacts + 1
Else
cnNumberexContacts = cnNumberexContacts + 1
End if
Case "group" nsNumberGroups = nsNumberGroups + 1
enumgroup(getobject("LDAP://" & replace(member.distinguishedName,"/","\/")))
Case "publicFolder" pfNumberPublicFolders = pfNumberPublicFolders + 1
Case "inetOrgPerson" ioNumberIorgPersons = ioNumberIorgPersons + 1
Case "msExchDynamicDistributionList" QbNumberQBDLs = QbNumberQBDLs + 1
enumQBDL(getobject("LDAP://" & replace(member.distinguishedName,"/","\/")))
End Select
numcheck = numcheck + 1
End if
end if
Next
end Sub

Sub enumQBDL(obdlobject)
if obdlobject.msExchDynamicDLBaseDN = "" then
strQuerydl = "<LDAP://" & strDefaultNamingContext & ">;" &
obdlobject.msExchDynamicDLFilter &
";mail,ObjectClass,distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
else
strQuerydl = "<LDAP://" & obdlobject.msExchDynamicDLBaseDN & ">;" &
obdlobject.msExchDynamicDLFilter &
";mail,ObjectClass,distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
end if
set com1 = createobject("ADODB.Command")
Com1.ActiveConnection = Conn
Com1.Properties("SearchScope") = 2 ' we want to search everything
Com1.Properties("Page Size") = 500 ' and we want our records in lots of 500
(must be < query limit)
wscript.echo strQuerydl
Com1.CommandText = strQuerydl
Set qdlRs = Com1.Execute
While Not qdlRS.eof
Set member = getobject("LDAP://" &
replace(qdlRS.fields("distinguishedName"),"/","\/"))
if Not trackmembers.exists(member.distinguishedName) Then
trackmembers.add member.distinguishedName,1
wscript.echo member.class & " " & member.displayname
If member.mail <> "" then
Select Case member.Class
Case "user" usNumberUsers = usNumberUsers + 1
Case "contact" wscript.echo
right(member.mail,(len(member.mail)-instr(member.mail,"@")))
If
sdSMTPDomains.exists(LCase(right(member.mail,(len(member.mail)-instr(member.mail,"@")))))
Then
cnNumberinContacts = cnNumberinContacts + 1
Else
cnNumberexContacts = cnNumberexContacts + 1
End if
Case "group" nsNumberGroups = nsNumberGroups + 1
enumgroup(getobject("LDAP://" & replace(member.distinguishedName,"/","\/")))
Case "publicFolder" pfNumberPublicFolders = pfNumberPublicFolders + 1
Case "inetOrgPerson" ioNumberIorgPersons = ioNumberIorgPersons + 1
Case "msExchDynamicDistributionList" QbNumberQBDLs = QbNumberQBDLs + 1
enumQBDL(getobject("LDAP://" & replace(member.distinguishedName,"/","\/")))
End Select
numcheck = numcheck + 1
End if
end if
qdlRS.movenext
wend

End Sub

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is. I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned) #Define Date to Query $StartDate = (Get-Date) $EndDate

Downloading a shared file from Onedrive for business using Powershell

I thought I'd quickly share this script I came up with to download a file that was shared using One Drive for Business (which is SharePoint under the covers) with Powershell. The following script takes a OneDrive for business URL which would look like https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filename.txt This script is pretty simple it uses the SharePoint CSOM (Client side object Model) which it loads in the first line. It uses the URI object to separate the host and relative URL which the CSOM requires and also the SharePointOnlineCredentials object to handle the Office365 SharePoint online authentication. The following script is a function that take the OneDrive URL, Credentials for Office365 and path you want to download the file to and downloads the file. eg to run the script you would use something like ./spdownload.ps1 ' https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filena

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script. So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.