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

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
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.