A little while ago I ran into a neat little freeware tool for Powershell called the Inactive Users Tracker PowerShell Cmdlet by a company called Netwrix.
This cmdlet in essence provided a nice, simple to use wrapper for consolidated last logon information for accounts in Active Directory (as you may be aware the lastlogon attribute is not replicated in 2003 environments, and can be a little difficult to average out using a script).
I initially started using the Netwrix module for reporting on inactive account information within my directory environments, however, the potential for it to be used as part of a much wider tool to weed out, and close down unused accounts and mailboxes was clear – so in this article I have come up with a sample script to give you some ideas on how you can automate the following processes using it:
- Finding accounts that have not been logged into for a defined period of time
- Export the mailboxes attached to those account to PST
- Remove the mailboxes
- Disable the Active Directory Account
- Move the AD Account to a specific OU
Unfortunately, Netwrix has now discontinued this tool in favour of a GUI version which I believe can be scheduled from the command line – however you can still download the version that I am using from here which I advise that you do as the functionality is really cool.
The script itself is loosely based upon an article that I published here in August of this year (2011) – but expands upon its functionality.
One thing that I must point out is that this script is a sample only and should not be used in production without modification.
If you intend to use this script in a production environment – you should look at implementing exclusions from the export and disable process – as typically there are a number of mailboxes in production that on face value are not logged into, but are serving a purpose.Additionally, you should also consider excluding accounts where the owner is on long term absence.
What I am saying is – use at your own risk!
Requirements
In order to make use of this script you will need to have the following pre-requisites installed on your Exchange (or Management Server):
- Exchange 2007 Management Tools
- Microsoft Outlook 2003 or 2007
- Quest Active Directory Cmdlets library
- Netwrix Powershell Library (requires a very quick installation)
Download
The script is available for download below – or you can copy it from the this page to a PS1 file on your Management / Exchange Server:
[ ExportMailboxesToPst-BasedonLogon.ps1 – 3KB ]
# Export Mailbox to PST, Disable Mailbox, Active Directory Account and Move to OU # Version 1.0 # Author: Andy Grogan # NOTE: This script REMOVES the mailbox from the account from the store # # Add-PSSnapin Quest.ActiveRoles.ADManagement Add-PSSnapin NETWRIXIUTPSSnapIn Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin $ErrorActionPreference = "SilentlyContinue" # Change the following to fit your requirements $gblInactiveDays = 50 $DestinationPSTPath = "X:\Psts" $ServiceAccount = "Administrator@ethan.local" function get-DNC{ Param ( $RDSE ) $DomainDNC = $RDSE.defaultNamingContext Return $DomainDNC } $NC = (Get-DNC([adsi]("LDAP://RootDSE"))) $DisabledAccountOU = "OU=DisabledUsers,"+$NC function apply_Permissions($strMailbox){ Remove-MailboxPermission -Identity $strMailbox -User $ServiceAccount -Deny -InheritanceType 'All' -AccessRights 'FullAccess' -Confirm:$false Add-MailboxPermission -Identity $strMailbox -User $ServiceAccount -AccessRights 'FullAccess' -Confirm:$false } function remove_permissions($strMailbox){ Remove-MailboxPermission -Identity $strMailbox -User $ServiceAccount -InheritanceType 'All' -AccessRights 'FullAccess' -Confirm:$false Add-MailboxPermission -Identity $strMailbox -User $ServiceAccount -Deny -AccessRights 'FullAccess' -Confirm:$false } function get_ADDomain(){ $strDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name return $strDomain } function disable_mailbox($strMailbox){ Disable-Mailbox $strMailbox -Confirm:$false } function get-dn ($SAMName) { $root = [ADSI]'' $searcher = new-object System.DirectoryServices.DirectorySearcher($root) $searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))" $user = $searcher.findall() if ($user.count -gt 1) { $count = 0 foreach($i in $user) { write-host $count ": " $i.path $count = $count + 1 } $selection = Read-Host "Please select item: " return $user[$selection].path } else { return $user[0].path } } function moveToDisabledOU($strDN){ move-QADObject -Identity $strDN -NewParentContainer $DisabledAccountOU } function get_InactiveAccounts(){ $Domain = get_ADDomain $Accounts = Get-NCInactiveUsers -domain $Domain -days $gblInactiveDays foreach($Usr in $Accounts){ $User = Get-User $Usr.AccountName if($User.RecipientType -eq 'UserMailbox'){ $path = Get-DN $User.samAccountName "'" + $path + "'" apply_Permissions $User.Identity Export_ToPST $User.Identity remove_Permissions $User.Identity disable_mailbox $User.Identity $QADPath = Get-QADUser -Identity $User.samAccountName $account=[ADSI]$path $account.psbase.invokeset("AccountDisabled", "True") $account.setinfo() Set-QADUser -Identity $user.samAccountName -Description "Account Disabled by PST Export Script" moveToDisabledOU $QADPath.DN } } } function export_ToPST($strMailID){ Export-Mailbox -Identity $strMailID -PSTFolderPath $DestinationPSTPath -Confirm:$false } get_InactiveAccounts
Using the script
Before the script can be scheduled for use, you will need to ensure that you have performed the following actions:
- Create an OU within your Active Directory infrastructure called “DisabledUsers” – see below

- Create a user account with the correct Exchange Permissions within your Exchange environment – the account needs to have a mailbox and have the following Exchange permissions:
- Exchange Server Administrator
- Local Administrator on the Management / Exchange Server
- You should then create a directory on your Management Server that will contain the exported PST files – in my example I have created a folder called “X:\Psts” – see below

- You should edit the script file and change the following values (located at the top of the script; to match the settings of your own environment)
$gblInactiveDays = 50 $DestinationPSTPath = "X:\Psts" $ServiceAccount = "Administrator@ethan.local"
The value of $gblInactiveDays is the seed value for how long an account has not been logged into – in my example the script will seek out Active Directory accounts that have not been logged into in 50 days.
The value of $DestinationPSTPath is the location on the local management server where the PST files will be stored.
The value of the $ServiceAccount should be the SMTP address of the user account that you have created to export the mail items from the Mailboxes.
- Once you have edited the script file to suite your needs, you should create a batch file that executes the script and can be scheduled via the Windows task manager.
In order to do this you should create a .cmd file with the following commands contained within it:
@Echo off
@Powershell -command "& {x:\<PathToScript>\ExportMailboxesToPst-BasedonLogon.ps1 }"
See below:

When you have done the above, you should then schedule it via the Windows Task manager to execute (using the service account that you have stipulated) at a time which is most appropriate to your environment.
Script Operation
It should be noted that depending on the size of the mailboxes concerned – the time it takes for this script to execute could vary from a few minutes to a few hours or even days) – you should take note of this when scheduling the task in the Windows scheduler.
When the script is executed it will perform the following actions:
- Seek out Active Directory Accounts with Mailboxes that have not been accessed in the $gblInactiveDays
- Apply full mailbox access permissions to the service account on each Mailbox
- Export the e-Mail items to a PST file located in the PST path location
- Disable the Exchange Mailbox
- Disable the AD account
- Move the AD account to the DisabledUsers OU
- Stamp the Description of the Account with the moniker that it was placed there by the script

Therefore after execution in the PST folder you should see PST’s for the accounts that complied with the filter – see below

In the DisabledUsers OU in Active Directory Users and Computers you should see a list of accounts that have been processed – see below

Within the Exchange Management Console you should see that the relevant account have been removed – see below
Before:

After:

I hope that this example provides a little inspiration for some folks and gives you some pointers on how you can automate the processes of removing old accounts within your Infrastructure.

























{ 3 comments… read them below or add one }
Thanks for the helpful scripting. I visited their site and that cmdlet isn’t available anymore.
Best,
Rob
Hiya Rob, yes that is correct – but you can still download it from http://www.softpedia.com/get/System/System-Miscellaneous/Inactive-Users-Tracker-PowerShell-Cmdlet.shtml
Cheers
A
Exchange EDB to PST Conversion is possible through Microsoft’s inbuilt utilities. If the correct permissions are not available, the process fails. Professional third party EDB to PST Converter tools can help to extract the data for all major versions.
http://edbtopstconverter.stellarservertools.com/