Exchange script to delete email items within a date range against a mailbox
Scenario: You want to delete mail items (not calendar or contact items) from all mailbox folders in a mailbox. The script performs a query for all email items between a date range.
Script:
$startdate = '01/01/1900' #specifies start date
$enddate = (get-date).adddays(-60) #specifies end date by subtracting 60 days
$enddate = $enddate.ToShortDateString() #converts end date to string.
$users = Import-csv C:\script\users.csv #imports list of users with the column heading 'name'
#Deletes email content between the two dates for each mailbox.
$users | ForEach {
search-mailbox $_.name -searchquery "kind:email AND Received:$startdate..$enddate" -deletecontent -force
}
Search-Mailbox has a 10,000 item limit that search-mailbox before it stops processing. Put it in a loop and let it run. The example below is for a single mailbox outside of the script above.
do {
Write-Host $i
search-mailbox mailboxname -searchquery "kind:email AND Received:1/1/1900..12/31/2012" -deletecontent -force
$i++
}
while ($i -le 30)
Script:
$startdate = '01/01/1900' #specifies start date
$enddate = (get-date).adddays(-60) #specifies end date by subtracting 60 days
$enddate = $enddate.ToShortDateString() #converts end date to string.
$users = Import-csv C:\script\users.csv #imports list of users with the column heading 'name'
#Deletes email content between the two dates for each mailbox.
$users | ForEach {
search-mailbox $_.name -searchquery "kind:email AND Received:$startdate..$enddate" -deletecontent -force
}
Search-Mailbox has a 10,000 item limit that search-mailbox before it stops processing. Put it in a loop and let it run. The example below is for a single mailbox outside of the script above.
do {
Write-Host $i
search-mailbox mailboxname -searchquery "kind:email AND Received:1/1/1900..12/31/2012" -deletecontent -force
$i++
}
while ($i -le 30)