PowerShell – Script to Delete Emails Older Than 7 Months or Specified Dates

exchangepowershell

I have problem with converting my Search-Mailbox command to another one. If you all know in the future as Search-Mailbox is retired. So I need to use another cmdlet for this command.

My working right now command with Search-Mailbox

Search-Mailbox -Identity test@test.comm -SearchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))" -deletecontet

I read a lot of times https://docs.microsoft.com/en-us/exchange/policy-and-compliance/ediscovery/delete-messages?view=exchserver-2019#step-2-delete-the-message and try do step by step and get this code.

New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com -ContentMatchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"

Start-ComplianceSearch -Identity "Remove older than 7 month messages"

New-ComplianceSearchAction -SearchName "Remove older than 7 month messages" -Purge -PurgeType SoftDelete

But its not work for me. getting error

Unable to execute the task. Reason: The search "Remove older than 8 month messages" is still running or it didn't

return any results. Please wait until the search finishes or edit the query and run the search again.

ADD my full PowerShell script

Start-Transcript


$smtpServer="smtp.office365.com" # Office 365 official smtp server 
$from = "IT Support <test@test.com>" # email from  
$logging = "Enabled" # Set to Disabled to Disable Logging 
$testing = "Disabled" # Set to Disabled to Email Users 
$testRecipient = "test@test.com"  
$date = Get-Date -format ddMMyyyy 

$Username = "test@test.com"
$Password = "test-" | ConvertTo-SecureString -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Password

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri  https://eur04b.ps.compliance.protection.outlook.com/powershell-liveid?PSVersion=5.1.17763.1007 -Credential $UserCredential -Authentication Basic –AllowRedirection

 Import-PSSession $Session

Get-ComplianceSearchAction
New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com  -ContentMatchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"
Start-ComplianceSearch -Identity "Remove older than 7 month messages"
New-ComplianceSearchAction -SearchName "Remove older than 7 month messages" -Purge -PurgeType SoftDelete 

Best Answer

Try:

New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com -ContentMatchQuery "(Received >= 01/12/2017 -and Received <= $((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"