The Search-Mailbox cmdlet can be used to perform various searches within a mailbox, and while it serves many needs, there are some searches that it can’t do. I wrote a PowerShell script to demonstrate how to perform a search of a mailbox (or mailboxes) using EWS, in this case looking for items of a particular message class. The script will search through all the folders of the mailbox (from the Top of Information store) and log all items found to a text file.
The search can be modified quite easily by changing the parameters in the SearchFolder function (modify $searchFilter accordingly), and also any processing can be added to the ProcessItem function (this function is called for every item that matches the search – in the sample, this is the function that logs to the text file).
The EWS Managed API needs to be installed on the machine running the script, but it does not need to be run on an Exchange server.
Script updated 11/7/14 to add support for searching archive mailboxes, and some other minor code changes.
To list any items that match the message class:
.\Search-MailboxForMessageClass <mailbox smtp address> <message class>
To delete any found items:
.\Search-MailboxForMessageClass <mailbox smtp address> <message class> -DeleteItems
-Mailbox: Specifies the mailbox to be accessed
-MessageClass: Specifies the message class of the items being searched
-SearchArchive: If this switch is specified, then the archive mailbox for the account (not the main mailbox) will be searched
-DeleteItems: If this switch is specified, any items found will be deleted (use with care!!)
-AuthUsername: Username used to authenticate with EWS (if omitted, the logged in user’s credentials are used)
-AuthPassword: Password used to authenticate with EWS
-AuthDomain: Domain used to authenticate with EWS
-Impersonate: Whether we are using impersonation to access the mailbox (defaults to false)
-EwsUrl: EWS Url (if omitted, then autodiscover is used)
-EWSManagedApiPath: Path to managed API (if omitted, a search of standard paths is performed)
-IgnoreSSLCertificate: Whether to ignore any SSL errors (defaults to false)
-LogFile: Log file – activity is logged to this file if specified (if omitted, it is just written to console)