Wednesday, February 21, 2018

Looking into the Microsoft Team's TeamChat folder in an Office365 Mailbox using EWS

If you looked at the folder structure in an Office365 Mailbox (or older Exchange Mailbox) using a MAPI editor so you could see all the Non_IPM_Subtree and hidden folders around 5 years ago it was a relatively simple picture. Today with the rapid pace of the change in Office365 its a little bit of minefield on new folders and hidden data that is stored and used by various applications in your Mailbox. A good case in point is the Files Hidden folder which Tony explains about in https://www.petri.com/mysterious-files-folder . Microsoft Teams is the new kid on the block in terms of collaboration applications that integrate into Mailboxes and other Office365 workloads. As you chat using the Microsoft Teams client as part of it compliance/discoverability process associated with Microsoft Teams a cloud-based process creates conversation items in a Hidden folder in your Office365 Mailbox called TeamChat (this is a Subfolder of the Conversation history). Because its a hidden folder users won't be able to see the content but the data stored is searchable (at the time of writing this there is very little official documentation that I can find Tony's post https://www.petri.com/teams-compliance-story and a few other forum posts give the best guide to what this is and how it works).

So because this is a hidden folder using the new Graph API won't work (although you can actually get to the Items using the Graph API by searching) so using EWS is the best approach for now as it gives the most flexibility if you want to start playing around with this data programmatically.

Binding to the folder in EWS

You could use a few different ways to get the TeamChat folder the approach I've used is to make use of the Extended Property TeamChatFolderEntryId which is set on the Root Folder of a Mailbox. This contains the PR_EntryId of the Folder in question so once you convert this to an EWSId using the CovertId operation in EWS you can then bind directly to the folder. eg here's what the code looks like


$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   $TeamChatFolderEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([System.Guid]::Parse("{E49D64DA-9F3B-41AC-9684-C6E01F30CDFA}"), "TeamChatFolderEntryId", [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary); $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties) $psPropset.Add($TeamChatFolderEntryId) $RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid,$psPropset) $FolderIdVal = $null
if ($RootFolder.TryGetProperty($TeamChatFolderEntryId,[ref]$FolderIdVal))  {    $TeamChatFolderId= new-object Microsoft.Exchange.WebServices.Data.FolderId((ConvertId -HexId ([System.BitConverter]::ToString($FolderIdVal).Replace("-","")) -service $service))    $TeamChatFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$TeamChatFolderId);   } }
Once you have access to the Folder you can start pulling basic folder statistics like the Number of Items, Sizes, AttachmentCounts etc (or more interestingly things you won't be able to do using Get-MailboxFolderstatitistics). But the more interesting thing to do is to look at the data stored on the conversation items, because these aren't your normal email Messages extended properties are used to hold the different data from Teams/Skype (also the normal Attachment and recipients collections of a message are also used). There are a few properties in use (which generally aren't documented either so if your interested I would suggest taking a look yourself with a MAPI editor at a few items). But the one that is of most interest to me anyway is the SkypeMessagePropertyBag which contains a lot the Metadata from the chat message. This is a string property that contain JSON so accessing and decoding it into something usable in Powershell is pretty easy using ConvertFrom-Json.

I've put together a sample script module for accessing this folder using EWS that has a couple of different functions. The first Get-TeamChatStats accesses the folder and does some simple aggregation of folder and items properties including the ConversationId from the SkypeMessagePropertyBag  to aggregated the number of conversations.


Get-TeamChatSkypeMessagePropertyBag enumerates all the Items in the TeamChat Folder and then outputs the SkypeMessagePropertyBag to the pipeline so you can then do any of you own aggregation or investigation etc eg



My current TeamChat data is pretty simple so there could be a few bugs in these scripts due to the limited data I had to run against. I've put the code up for these script on GitHub at https://github.com/gscales/Powershell-Scripts/blob/master/TeamChatStats.ps1 so fell free to log an issue you experience and I'll path the code.

Friday, February 02, 2018

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

Preface

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 https://support.office.com/en-us/article/run-a-content-search-in-the-office-365-security-compliance-center-61852fd9-fe8a-4880-a339-cb19ed3bff4a 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 https://technet.microsoft.com/en-us/library/bb267022(v=exchg.80).aspx

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 https://support.office.com/en-us/article/keyword-queries-and-search-conditions-for-content-search-c4639c2e-7223-4302-8e0d-b6e10f1c3be3#emailproperties
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 https://support.microsoft.com/en-us/help/3093866/the-number-of-search-results-can-t-be-more-than-250-when-you-search-em 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 https://www.powershellgallery.com/packages/Exch-Rest 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 'James@domain.com'  | 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 'From:James@domain.com'  | 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 'james@domain.com' | 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 'from:james@domain.com' | 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 user@domain.com
To Restrict the results to a particular name SearchFolder you can use
Get-EXRSearchFolders -MailboxName user@domain.com -FolderName 'Voice Mail'
To enumerate the linked Items (Search Criteria items) from the Voice Mail SearchFolder use
$VoiceMail = Get-EXRSearchFolders -MailboxName user@domain.com -FolderName 'Voice Mail'
Get-EXRFolderItems  -MailboxName user@domain.com -Folder $voicemail