Skip to main content

Removing Disabled Users from Distribution lists via a script

One thing that I seem to do with monotonous regularity is disable user accounts as people churn though the companies that I work for. Usually once an account is disabled the chances of it being re-enabled while possible are always slim. One of the things that mostly gets forgotten when disabling an account is to also remove it from any distribution lists that account maybe in. Now with the new hot-fix this is not as much of a problem because a disabled mailbox can now be configured to still receive email. However it is still desirable for these disabled accounts not to be receiving email from distribution lists. Instead of going though each disabled user to work out if it’s a member of any distribution list and then remove it I decided to create a script that would fist let me list all the disable users that are in a distribution lists and also have an option so it will remove these users from that group.

For the script itself I’ve used ADSI and the ADO data shaping provider again. As in the past the ADO data shaping provider is great if you want to create hierarchal datasets which is perfect for what I want to do here. Basically the script first goes though and creates a parent record set with the names of all the mail enabled groups in Active directory. A second ADSI query is then performed which does a bitwise filter to retrieve a recordset of all the disabled users with a mailbox. A child recordset is then created with an entry for each group a user is in. The two recordsets are then related on the Group’s DistinguishedName which then gives me a retrievable hierarchy such as

GroupName-|
|-UserName

The display section of the code then just looks at groups with at least 1 disabled user as a member. Some extra code is added to skip the system mailboxes and some ADSI code also is used to remove the user from the group if the script is being run in remove mode.

To run the script in display mode just run the script without any command-line parameters eg

Cscript.disabusers.vbs

To run the script in remove mode meaning that it will remove the disabled accounts from the group memberships of any mail-enabled groups (this script does not different between group types) run the script with remove as the command-line parameter eg

Cscript disabusers.vbs remove

I’ve put a downloadable copy of the script here the code itself looks like


if wscript.arguments.length = 0 then
wscript.echo "Display Mode"
else
if lcase(wscript.arguments(0)) = "remove" then
mode = "remove"
wscript.echo "Remove Mode"
else
wscript.echo "Display Mode"
end if
end if
wscript.echo
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
set conn1 = createobject("ADODB.Connection")
strConnString = "Data Provider=NONE; Provider=MSDataShape"
conn1.Open strConnString
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
set objParentRS = createobject("adodb.recordset")
set objChildRS = createobject("adodb.recordset")
strSQL = "SHAPE APPEND" & _
" NEW adVarChar(255) AS GRPDisplayName, " & _
" NEW adVarChar(255) AS GRPDN, " & _
" ((SHAPE APPEND " & _
" NEW adVarChar(255) AS USDisplayName, " & _
" NEW adVarChar(255) AS USDN, " & _
" NEW adVarChar(255) AS USGRPDisplayName, " & _
" NEW adVarChar(255) AS USGRPDN " & _
")" & _
" RELATE GRPDN TO USGRPDN) AS rsGRPUS "
objParentRS.LockType = 3
objParentRS.Open strSQL, conn1
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
GALQueryFilter = "(&(mailnickname=*)(|(objectCategory=group)))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter &
";distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
Com.ActiveConnection = Conn
Com.CommandText = strQuery
Set Rs = Com.Execute
while not rs.eof
objParentRS.addnew
objParentRS("GRPDisplayName") = rs.fields("displayname")
objParentRS("GRPDN") = rs.fields("distinguishedName")
objParentRS.update
rs.movenext
wend
GALQueryFilter =
"(&(&(mailnickname=*)(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=2)))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter &
";distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
Com.ActiveConnection = Conn
Com.CommandText = strQuery
Set Rs1 = Com.Execute
Set objChildRS = objParentRS("rsGRPUS").Value
while not rs1.eof
if instr(rs1.fields("displayname"),"SystemMailbox{") = 0 then
set objuser = getobject("LDAP://" & rs1.fields("distinguishedName"))
For each objgroup in objuser.groups
objChildRS.addnew
objChildRS("USDisplayName") = rs1.fields("displayname")
objChildRS("USDN") = rs1.fields("distinguishedName")
objChildRS("USGRPDisplayName") = objgroup.name
objChildRS("USGRPDN") = objgroup.distinguishedName
objChildRS.update
next
end if
rs1.movenext
wend
objParentRS.MoveFirst
wscript.echo "GroupName,Disabled User's Name"
wscript.echo
Do While Not objParentRS.EOF
Set objChildRS = objParentRS("rsGRPUS").Value
if objChildRS.recordCount <> 0 then
Do While Not objChildRS.EOF
Wscript.echo objParentRS.fields("GRPDisplayName") & "," &
objChildRS.fields("USDisplayName")
if mode = "remove" then
set objgroup = getobject("LDAP://" & objChildRS.fields("USGRPDN"))
Set objUser = getobject("LDAP://" & objChildRS.fields("USDN"))
objGroup.Remove(objUser.AdsPath)
objgroup.setinfo
wscript.echo "User-Removed"
end if
objChildRS.MoveNext
loop
end if
objParentRS.MoveNext
Loop

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 Gr...

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 ...

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 ...
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.