Skip to main content

Searching Mailbox folders using the REST API In Powershell on Office365 and Exchange 2016


Searching Mailboxes is something I've written a fair bit about in the past but in this article I'm going to cover how searching has been surfaced in the new REST API on Office365 and Exchange 2016.  The first place to go when considering searching in Office365 is the Security and Compliance center it offers the most feature rich and realistic search experience that is difficult to replicate with client facing Mailbox API's (eg things like RBAC's delegated access rights, litigation holds etc). Given the amount of data that can be stored in Mailboxes now its important to have a realistic expectation of the time it will take and difficulty of searching 100,000's items in multiple folders or millions of items in an Archive is important (at the time of writing Archives aren't accessible using the REST API).

Searching Mailboxes

Within an Office365 Mailbox there are number of different methods for performing a Search using the REST API for particular items within a particular Mailbox folder or across all folders in a mailbox. Depending on the properties you want to search on and the amount of data you expect to return in your search you should select the most appropriate method to use.

Using filters (or Restrictions)

Restrictions are the standard way in which searches are normally carried out in Outlook and Exchange, restrictions are property based searches on one or more properties and may involve a number of operators such as equals, greatorthan, lessthan, contains (for substrings) or startswith. In the REST API restriction are implemented via the $filter Query Parameter. Because the raw content is queried this type of search can take longer to perform if the underlying folder has a larger number of items or the restriction being used is very complicated. A common issue that can occur using filters is the Query will timeout or will be throttled because of the overall load it produces on the server. Some more background on restrictions can be found

Using KQL (or Exchange Search)

Exchange Search is the full text indexing feature of Exchange which indexes contents automatically (asynchronously) as email arrives in a Mailbox.This type of Search utilizes the KQL (Keyword Query Logic) that is also used with in Share-point for query processing. This is the faster and more efficient method of searching a Mailbox because it utilizes Full Text Indexes rather then needing to query the raw content and should be the preferred starting point for search. However there are some limitations on the properties that can be searched using this method and also on the amount of results that will be returned by a query. In the REST API KQL queries are performed using the $search Query Parameter.
Property restrictions : As Exchange only indexes certain properties for performance reason only certain properties can be searched using KQL a full list of the indexed properties the can be used can be found
Maximum Result Sets: Exchange limits the maximum result set of Exchange Search queries to 250 Items in REST and EWS. with OnPrem Servers this value is adjustable via the MaxHitsForFullTextIndexSearches property however in Exchange OnLine (Office365) you can't adjust that value and need to work under the 250 item ceiling.

Using SearchFolders

Search Folders are Special Mailbox folders that contain no items but return linked Items based on a predefined search criteria (usually the same as you would use in Filters). Because these are constantly updated asynchronously by the Exchange Server they offer better performance when retrieving items based on a search criteria then doing a normal search using a filter. Search Folders are a good choice if you have static queries that don't require any dynamic input or you need to have a search that spans multiple folders. You do need to be aware that overuse of Search Folders can cause poor performance and they are updated by a background process so new items may not be instantly available as apposed to querying the Mailbox folder directly. Some more background information on Search Folders can be found
Currently there is no way of creating a SearchFolder programmaticly using the REST API but this can be done using EWS.

Search Examples using the Search-EXRMessage cmdlet from the Exch-Rest Module

Several of the cmdlets in the Exch-REST Module allows the entering of both the Filter and Search criteria however the cmdlet specifically designed for search is the Search-EXRMessage cmdlet
Using Raw KQL
The -KQL Parameter allows you enter raw KQL to be used as a Mailbox Search if you do use this approach you should take care that some characters need to be escaped correct. Eg when search for an exact phrase in KQL the phrase should be encolesd in double quotes. When doing this in REST these double quotes need to be escape. Eg so if you where search for email with the subject has the following keywords you could use -KQL "subject:'termone termtwo'" where if you want to search for a phrase you should use -KQL 'subject:"this is a phrase""
Specifying the folders to Search
By default the Search-EXRMessage cmdlet will search all the Mail folders in a Mailbox using the AllItems Search Folder if no folder is specified in the cmdline. To limit the Search to a particular folder you can specify the folder using the -FolderPath eg
Search-EXRMessage -FolderPath \Inbox -KQL 'subject:"Happy Days"'
or use the -Wellknown parameter to specify one of the default folder such as Inbox or SentItems eg
Search-EXRMessage -Wellknow SentItems -KQL 'subject:"Happy Days"'
Returning Attachments details within Search Results
Returning attachment details when search for objects requires extra requests be made to the server which will affect the performance of search greatly so this isn't done by default. However if its import for you to get this information because of the type of search that you are trying to do then you can use the -ReturnAttachments swich. Not when using the -AttachmentKQL switch this is submitted by default.
Finding a Message from a Particular Sender
Find a Message from a Particular Sender by Name or Email Address using a Filter
by Email
Search-EXRMessage -MailboxName user@domain -from ''  | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a messages from a Particular Sender by Name or Email Address using KQL
by Name
Search-EXRMessage -MailboxName user@domain -kql 'From:James'  | select Subject,SenderEmailAddress,SenderName,FolderPath
by Email Address
Search-EXRMessage -MailboxName user@domain -kql ''  | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message from a Particular Sender on a Particular Date
using a Filter
Search-EXRMessage -MailboxName user@domain -ReceivedtimeFrom ([DateTime]::Parse('2018-01-01')) -ReceivedtimeTo ([DateTime]::Parse('2018-01-02')) -from '' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -ReceivedtimeFromKQL ([DateTime]::Parse('2018-01-01')) -ReceivedtimeToKQL ([DateTime]::Parse('2018-01-02')) -KQL '' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message with a Particular Subject (Exact Match)
using a Filter
Search-EXRMessage -MailboxName user@domain -subject 'And the Subject is' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -SubjectKQL 'And the Subject is' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Subject contains a phrase
using a Filter
Search-EXRMessage -MailboxName user@domain -SubjectContains 'And the Subject' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -KQL "Subject:'And the Subject'" | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Subject starts with a phrase using a Filter
Search-EXRMessage -MailboxName user@domain -SubjectStartsWith 'And the Subject' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Body contains a phrase
using a Filter
Search-EXRMessage -MailboxName user@domain -BodyContains 'Summer Sales' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -BodyKQL "Sumber Sale" | select Subject,SenderEmailAddress,SenderName,FolderPath
Find Attachments
You can search for attachments using the full attachment name or a partial name like the extension if you want to find all email with word documents for example.
Using KQL
Search-EXRMessage -MailboxName user@domain -AttachmentKQL ".doc" -ReturnAttachments 

Using SearchFolders

To use a Search folder you first need to know the FolderId value of the SearchFolder you wish to use, SearchFolder should be available under the NON_IPM_Subtree Finder folder. To get the available search folders in a Mailbox you can use the Get-EXRSearchFolders Cmldet eg
Get-EXRSearchFolders -MailboxName
To Restrict the results to a particular name SearchFolder you can use
Get-EXRSearchFolders -MailboxName -FolderName 'Voice Mail'
To enumerate the linked Items (Search Criteria items) from the Voice Mail SearchFolder use
$VoiceMail = Get-EXRSearchFolders -MailboxName -FolderName 'Voice Mail'
Get-EXRFolderItems  -MailboxName -Folder $voicemail

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is. I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned) #Define Date to Query $StartDate = (Get-Date) $EndDate

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script. So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this

EWS Managed API and Powershell How-To series Part 1

I thought I'd start the year with a series of posts that goes back over the basics of using the EWS Managed API from Powershell and provides a modular remarked example that you can easily cut and paste to build your own scripts. Along the way in this series I'll show a whole bunch of examples around specific things. As a starting point for versions this will be Powershell Version 2.0  and the EWS Managed API 1.1 (which will soon change to 1.2 once released) The starting point for any EWS script your going to write is connecting to Exchange for which there are three important pieces of information you will need. Firstly you need to know the version of Exchange your running in this script its going to be held in the following variable $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1 Other valid values for Exchange 2007 would be $ExchangeVersion = [Microsoft.Exchange.Web
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.