Purge emails powershell

The joys of email management!

To purge emails using PowerShell, you'll need to use the Get-Mailbox cmdlet to retrieve the mailbox, and then use the Search-Mailbox cmdlet to find the emails you want to delete. Finally, use the Remove-Mailbox cmdlet to delete the emails.

Here's an example script to get you started:

# Set the mailbox to purge
$mailbox = "[email protected]"

# Set the date range for the emails to purge (e.g., 30 days ago)
$dateRange = (Get-Date).AddDays(-30)

# Search for emails older than the date range
$searchResults = Search-Mailbox -Mailbox $mailbox -SearchQuery "Received:<$dateRange" -DeleteContent

# Confirm the results before deleting
$searchResults | Format-Table -AutoSize
Read-Host "Press Enter to delete the emails"

# Delete the emails
Remove-Mailbox -Mailbox $mailbox -Force

Let me explain what each line does:

  1. Set the mailbox to purge: Replace [email protected] with the email address of the mailbox you want to purge.
  2. Set the date range for the emails to purge: This sets the date range for the emails to purge. In this example, we're looking for emails older than 30 days ago. You can adjust this to suit your needs.
  3. Search for emails older than the date range: The Search-Mailbox cmdlet searches for emails in the specified mailbox that match the search query. In this case, we're searching for emails received before the date range.
  4. Confirm the results before deleting: The Format-Table cmdlet displays the search results in a table. The Read-Host cmdlet prompts you to press Enter to confirm the deletion.
  5. Delete the emails: The Remove-Mailbox cmdlet deletes the emails from the mailbox. The -Force parameter forces the deletion without prompting for confirmation.

Before running this script, make sure you have the Exchange PowerShell module installed and configured on your system. You can do this by running the following command:

Install-Module -Name ExchangeOnline

Also, be cautious when running this script, as it permanently deletes emails without prompting for confirmation. Make sure to test the script in a non-production environment before running it on a live mailbox.