Remove mailbox of disabled AD user accounts

A downloadable copy of the script is available here.


So...for my latest scripting foray, I came up with a little script to do the following:

  • Find all User accounts that have a SamAccountName that matches a particular filter, and that DO NOT have their passwords set to Never Expire (so we don't hit service accounts, etc)
  • If the account is a member of a particular group, leave the mailbox intact, but set a particular retention policy on it (in this case, a 14 day policy)
  • If the disabled account is NOT a member of the aforementioned group, remove the Exchange attributes from the AD account, or essentially, disable the mailbox
  • And, that's pretty much it. I also logged all accounts that we touch to a file, and added a timer so I’d know how long it takes the script to run.

 For this particular application, the script was written for and run against an Exchange 2007 environment FROM the Exchange management shell. Theoretically it should work with other versions as well, but I have yet to test that scenario.

 Also, please note that the script requires the Active Directory Module to be imported, so it cannot be run from instances of Exchange 2007 that are running on Windows Server 2003.

 For my purposes, all user account names have a 6 digit number in them. To make sure I grab only those accounts, a regex filter was used against the SamAccountName attribute so that only those accounts are matched, which is what the "\d{6}" is. You can take out that portion, or update the filter to match your needs.

Hopefully this is a good example of how you can automate your more routine tasks. Enjoy!

Here is a snippet of the script. Please go HERE to download the full copy.. 

$stopwatch = New-Object system.Diagnostics.Stopwatch


$date = Get-Date -format MMddyy

$LogFile = "c:\LogFile_$date.txt"

$grouppath = "CN=GG-Termed-Retain,DC=contoso,DC=com" #Change this group name to match your environment!!!


write-host "Please wait while I import the active directory module..."

Import-Module ActiveDirectory

start-sleep -s 15


$DisabledAccounts = get-mailbox -resultsize Unlimited –ErrorAction SilentlyContinue –WarningAction SilentlyContinue | where {($_.UserAccountControl -eq "AccountDisabled, NormalAccount") –and ($_.RecipientTypeDetails –ne “RoomMailbox”) –and ($_.SamAccountName –match “\d{6}”)}


$Count = $DisabledAccounts.Count


Thanks, Kris.