Searching Emails using Power shell

Recently I came across a request to search for all emails sent out by a user that included attachments. I ended up getting that report using a power shell commands.

To search for all sent emails with attachments in a mailbox using Power Shell, you can use the `Search-Mailbox` cmdlet available in Exchange Online or on-premises Exchange environments. The `Search-Mailbox` cmdlet allows administrators to search mailboxes for specific criteria and perform various actions on the results.

Here’s an example of how to use `Search-Mailbox` to find all sent emails with attachments in a specific mailbox.

Prerequisites

1. Exchange Online Management: Ensure you have the Exchange Online Management module installed and connected to your Exchange Online service. You can install the module using:

    Install-Module -Name ExchangeOnlineManagement

2. Permissions: Ensure you have the necessary permissions to perform mailbox searches. Typically, you need to be a member of the `Discovery Management` role group OR you can use Global Admin.

Connecting to Exchange Online

First, connect to Exchange Online:

# Import the Exchange Online Management module

Import-Module ExchangeOnlineManagement

Connect to Exchange Online (you will be prompted for credentials)

    Connect-ExchangeOnline -UserPrincipalName youradmin@domain.com

Using Search-Mailbox to Find Sent Emails with Attachments

#Define the mailbox to search

    $mailbox = “user@domain.com”

    $searchQuery = ‘HasAttachments:true AND folderpath:”\Sent Items”‘

# Perform the search and output the results

    Search-Mailbox -Identity $mailbox -SearchQuery $searchQuery -LogOnly -LogLevel Full

OR

Search-Mailbox -Identity $mailbox -SearchQuery $searchQuery -TargetMailbox user@domain.com –

TargetFolder “SearchedEmails” -LogLevel Full

The search results are logged, and you can review them to see details of the emails that matched the criteria. The logs will include information such as the subject, sender, recipient, and attachment details.

Or you can log on to the mailbox user@domain.com and logs should have been logged under a folder called “SearchedEmails”.

Following will search and delete the content as per the criteria provided, but it’s recommended to first log so you know for sure what is it that you are deleting.

search-mailbox -Identity $mailbox -SearchQuery {(Received:06/01/2021..08/03/2021)} -DeleteContent

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑