«

Jan 18

Print this Post

Soft Deleted Mailbox Cleanup

### SoftDeleted Mailbox Cleanup ###
# Our Retention policy is set deleted mailbox cleanup at 3650 Days.
# Moved mailboxes leave behind SoftDeleted copies that are not needed beyond ensuring that the move was successful.
# This script will remove all SoftDeleted mailbox copies over 3o days old.
### ###

### Load Exchange Powershell Management Modules ###
Write-Host "Loading Exchange Management Powershell Modules"
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010, Microsoft.Exchange.Management.PowerShell.Setup , Microsoft.Exchange.Management.Powershell.Support
Write-Host " "
#####

# Load a list of Mailbox Databases
$dbs = Get-MailboxDatabase

# Set the cut-off date for removing mailboxes
$cutOffDate = (get-date).AddDays(-30)

# $outData can be used for logging output
$outData = @()

### Loop Through Each Mailbox Database
foreach($db in $dbs){

# Load all mailboxes that are in a SoftDeleted state older than the cut-off date
$mbs = Get-MailboxStatistics -database $db | WHERE { $_.DisconnectReason -eq "SoftDeleted" -and $_.DisconnectDate -lt $cutOffDate }

### Loop through each mailbox, generate log data, and remove the SoftDeleted mailbox copy ##
foreach($mb in $mbs){
$outLine = $mb | SELECT @{Label="Database";Expression={$db}},DisplayName,DisconnectReason,DisconnectDate,@{Label="SizeMB";Expression={$_.TotalItemSize.Value.ToMB()}}
$outData += $outLine

# Write out the Mailbox copy we are removing
$outLine | select Database,DisplayName,DisconnectDate
# Remove the SoftDeleted mailbox copy
Remove-StoreMailbox -Database $db -Identity $mb.MailboxGuid -MailboxState SoftDeleted -confirm:$false
# the Update-StoreMailboxState will cause get-MailboxStatistics to reflect the mailbox removal immediately
Update-StoreMailboxState -Database $db -Identity $mb.MailboxGuid
}
}
### ###

# $Outdata can be printed to the screen or exported to a file for logging purposes.
#$outData | ft -AutoSize

Permanent link to this article: https://www.wperry.net/code/soft-deleted-mailbox-cleanup/

Leave a Reply

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