November 10, 2011

Using Powershell to Archive Mailboxes to PST based upon the AD lastLogonTime in Exchange 2007…

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!


In order to make use of this script you will need to have the following pre-requisites installed on your Exchange (or Management Server):


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 Microsoft.Exchange.Management.PowerShell.Admin

$ErrorActionPreference = "SilentlyContinue"

# Change the following to fit your requirements

$gblInactiveDays = 50
$DestinationPSTPath = "X:\Psts"
$ServiceAccount = "[email protected]"

function get-DNC{

     Param (

       $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

          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.psbase.invokeset("AccountDisabled", "True")
            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


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 = "[email protected]"

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





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.

Exchange 2007 Articles, Powershell 4 Replies to “Using Powershell to Archive Mailboxes to PST based upon the AD lastLogonTime in Exchange 2007…”
Andy Grogan
Andy Grogan


4 thoughts on “Using Powershell to Archive Mailboxes to PST based upon the AD lastLogonTime in Exchange 2007…

    Author’s gravatar

    Thanks for the helpful scripting. I visited their site and that cmdlet isn’t available anymore.



    Author’s gravatar

    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.

    Author’s gravatar

    Thanks for this, have used it off and on for years now.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.
%d bloggers like this: