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:
Set the mailbox to purge
: Replace[email protected]
with the email address of the mailbox you want to purge.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.Search for emails older than the date range
: TheSearch-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.Confirm the results before deleting
: TheFormat-Table
cmdlet displays the search results in a table. TheRead-Host
cmdlet prompts you to press Enter to confirm the deletion.Delete the emails
: TheRemove-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.