Script To Export Then Disconnect an Exchange Mailbox

A situation came up where I needed to be able to remove a user’s mailbox, but his supervisor wanted a copy of the contents in the form of a pst file. It would be easy enough to export the mailbox then go back later to disable it manually, but where’s the fun in that? This script accomplishes the same thing in a much more hands-off way.

Here’s how:

  1. >Accepts a command line option for the username, displayname, alias, etc.
  2. >Exports the mailbox to a pre-set network location.
  3. >Waits for the export to complete before disabling the mailbox. (This will monopolize the PowerShell window, so you might want to run it in a separate PS instance. You can do this from within another script using “Start-Process powershell.exe -argument ‘-command “ExportAndDisco.ps1 username”‘”

This script is specifically for Exchange 2010, but should work on 2013 with the appropriate modifications.

A PowerShell script to export and then disconnect an Exchange mailbox.

# Defines the commandline parameter as $mbx.
param([string]$mbx)

# Defines the export path. This value MUST be a UNC path
# and MUST end with a back slash.
$ExportPath = "\\servername\server\"

# Loads Exchange 2010 PowerShell snapin if it's not already loaded.
if ((get-pssnapin -name` 
    Microsoft.Exchange.Management.PowerShell.E2010 `
    -EA silentlycontinue) -eq $null) {
	add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
}

# Checks for an existing export job.
if ((Get-MailboxExportRequest | ?{$_.FilePath -like "*$mbx.pst"}) {
    write-host "There is an existing export request" `
	-ForegroundColor Red
    write-host "for this mailbox. Remove that request " `
	-ForegroundColor Red
    write-host "and try again." `
	-ForegroundColor Red
    exit
}

# Exports the mailbox. 
New-MailboxExportRequest $mbx -FilePath `
	$ExportPath+$mbx+".pst" -BadItemLimit 50 `
	-confirm:$false

# Checks the export status every 60 seconds. Continues when the
# status = "Completed".
do {sleep 60}
while ((Get-MailboxExportRequest | `
	?{$_.FilePath -like "*$mbx.pst"}).Status -ne "Completed")
	
# Disables the mailbox.
Disable-Mailbox $mbx -Confirm:$false

Leave a Reply

Your email address will not be published.