Skip to main content

Pull Subscription Mailbox Item move tracking script MEC sample 2

This is the second of the Powershell script samples from my MEC talk last week. The idea behind this script is to track the movement of Items in a Mailbox between folders using Pull Notifications in EWS, you can read more about how Pull notifications work here .  This script takes advantage of the fact that when you enable Single Item Recovery any deletes you make in a Mailbox (hard or soft) the Items aren't deleted rather moved to the Dumpster v2 RecoverableItems folders. So if you track all the move notification events you can track both the movement of Messages by rules, users or deletes. eg the results look like



I've created two different versions of this script, the first version subscribes to all folders in a Mailbox and runs continuously against the Mailbox and does a GetEvents request every minute to retrieve the latest events from all folders in a Mailbox and then logs that to file.

The second version just subscribes to the Inbox folder and saves the subscription information out to file when you run it the first time. Then the next time you run the script it will use the saved SubscriptionId and Watermark value to get all the events since the script was last run. Pull Subscriptions have a timeout of 1440 minutes (which is 1 day) so if you are going to run this version you need to run it with a maximum gap of 1 day. The idea of this second version was just to track inbox fan-out of messages rather then subscribing to all folders like the first version.

Both of these scripts use EWS Impersonation which must be configured for the account your going to run the script as. When you run the script you need to pass in the Mailbox to run against and the timeout value in minutes for subscription which needs to between 1 and 1440 eg

./pullSubTrackWm.ps1 jcool@msgdevelop.onmicrosoft.com 1440

I've put a download of both scripts here the code itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2. $MailboxName = $args[0]  
  3. $duration = $args[1]  
  4. $sw = [system.diagnostics.stopwatch]::startNew()  
  5. $Error.Clear()  
  6. $Script:changeLog = "c:\temp\ChangeLog-$(get-date -f yyyy-MM-dd).csv";   
  7. if(-Not(Test-Path -Path $Script:changeLog)){  
  8.     Add-Content -Path $Script:changeLog ("EventTime,MessageDateTimeReceived,Subject,MovedFrom,MovedTo,LastModifiedName")  
  9. }  
  10. #Add-Content -Path $Script:changeLog ("Start Log" + (Get-Date).ToString())   
  11.   
  12. ## Load Managed API dll    
  13. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  14. Add-Type -AssemblyName System.Runtime.Serialization  
  15. ## Set Exchange Version    
  16. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  17.     
  18. ## Create Exchange Service Object    
  19. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  20.     
  21. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  22.     
  23. #Credentials Option 1 using UPN for the windows Account    
  24. $psCred = Get-Credential    
  25. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  26. $service.Credentials = $creds        
  27.     
  28. #Credentials Option 2    
  29. #service.UseDefaultCredentials = $true    
  30.     
  31. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  32.     
  33. ## Code From http://poshcode.org/624  
  34. ## Create a compilation environment  
  35. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  36. $Compiler=$Provider.CreateCompiler()  
  37. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  38. $Params.GenerateExecutable=$False  
  39. $Params.GenerateInMemory=$True  
  40. $Params.IncludeDebugInformation=$False  
  41. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  42.   
  43. $TASource=@' 
  44.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  45.     public class TrustAll : System.Net.ICertificatePolicy { 
  46.       public TrustAll() {  
  47.       } 
  48.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  49.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  50.         System.Net.WebRequest req, int problem) { 
  51.         return true; 
  52.       } 
  53.     } 
  54.   } 
  55. '@   
  56. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  57. $TAAssembly=$TAResults.CompiledAssembly  
  58.   
  59. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  60. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  61. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  62.   
  63. ## end code from http://poshcode.org/624  
  64.     
  65. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  66.     
  67. #CAS URL Option 1 Autodiscover    
  68. $service.AutodiscoverUrl($MailboxName,{$true})    
  69. "Using CAS Server : " + $Service.url     
  70.   
  71.   
  72. #CAS URL Option 2 Hardcoded    
  73.     
  74. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  75. #$service.Url = $uri      
  76.     
  77. ## Optional section for Exchange Impersonation    
  78.     
  79. $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  80. #check Anchor header for Exchange 2013/Office365    
  81. if($service.HttpHeaders.ContainsKey("X-AnchorMailbox")){    
  82.     $service.HttpHeaders["X-AnchorMailbox"] = $MailboxName    
  83. }else{    
  84.     $service.HttpHeaders.Add("X-AnchorMailbox"$MailboxName);    
  85.     $service.HttpHeaders.Add("X-PreferServerAffinity","true");  
  86. }    
  87. "AnchorMailbox : " + $service.HttpHeaders["X-AnchorMailbox"]    
  88.   
  89.   
  90.   
  91. $FolderCollection = New-Object System.Collections.Hashtable  
  92. #Define Function to convert String to FolderPath    
  93. function ConvertToString($ipInputString){    
  94.     $Val1Text = ""    
  95.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){    
  96.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))    
  97.             $clInt++    
  98.     }    
  99.     return $Val1Text    
  100. }   
  101.   
  102. #Define Extended properties    
  103. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  104. $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)    
  105. #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling    
  106. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  107. #Deep Transval will ensure all folders in the search path are returned    
  108. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  109. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  110. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);    
  111. #Add Properties to the  Property Set    
  112. $psPropertySet.Add($PR_Folder_Path);    
  113. $fvFolderView.PropertySet = $psPropertySet;    
  114. #The Search filter will exclude any Search Folders    
  115. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  116. $fiResult = $null    
  117. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox    
  118. do {    
  119.     $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilter,$fvFolderView)    
  120.     foreach($ffFolder in $fiResult.Folders){    
  121.         $foldpathval = $null    
  122.         #Try to get the FolderPath Value and then covert it to a usable String     
  123.         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))    
  124.         {    
  125.             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)    
  126.             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }    
  127.             $hexString = $hexArr -join ''    
  128.             $hexString = $hexString.Replace("FEFF""5C00")    
  129.             $fpath = ConvertToString($hexString)    
  130.         }    
  131.         "FolderPath : " + $fpath    
  132.         $FolderCollection.Add($ffFolder.Id.UniqueId,$fpath)  
  133.     }   
  134.     $fvFolderView.Offset += $fiResult.Folders.Count  
  135. }while($fiResult.MoreAvailable -eq $true)    
  136.   
  137. function GetEventsRequest{    
  138. param (  
  139.   $SubscriptionId="$( throw 'SubscriptionId is a mandatory Parameter' )",  
  140.   $Watermark="$( throw 'Credentials is a mandatory Parameter' )",  
  141.   $ImpersonationHeader="$( throw 'ImpersonationHeader is a mandatory Parameter' )"  
  142. )  
  143. process{  
  144. Write-Host($SubscriptionId)  
  145. $request = @" 
  146. <?xml version="1.0" encoding="utf-8"?> 
  147. <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
  148.   xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> 
  149.    <soap:Header> 
  150.     <t:RequestServerVersion Version="Exchange2010_SP2"/> 
  151.     <t:ExchangeImpersonation> 
  152.       <t:ConnectingSID> 
  153.         <t:SmtpAddress>$ImpersonationHeader</t:SmtpAddress> 
  154.       </t:ConnectingSID> 
  155.     </t:ExchangeImpersonation> 
  156.   </soap:Header> 
  157.   <soap:Body> 
  158.     <GetEvents xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"> 
  159.       <SubscriptionId>$SubscriptionId</SubscriptionId> 
  160.       <Watermark>$Watermark</Watermark> 
  161.     </GetEvents> 
  162.   </soap:Body> 
  163. </soap:Envelope> 
  164. "@  
  165. return $request  
  166. }  
  167. }  
  168. $DeletionsID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::RecoverableItemsDeletions,$MailboxName);  
  169. $Deletions = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$DeletionsID)  
  170. $evEvents = new-object Microsoft.Exchange.WebServices.Data.EventType[] 6  
  171. $evEvents[0] = [Microsoft.Exchange.WebServices.Data.EventType]::Copied  
  172. $evEvents[1] = [Microsoft.Exchange.WebServices.Data.EventType]::Created  
  173. $evEvents[2] = [Microsoft.Exchange.WebServices.Data.EventType]::Deleted  
  174. $evEvents[3] = [Microsoft.Exchange.WebServices.Data.EventType]::Modified  
  175. $evEvents[4] = [Microsoft.Exchange.WebServices.Data.EventType]::Moved  
  176. $evEvents[5] = [Microsoft.Exchange.WebServices.Data.EventType]::NewMail  
  177. $psSub = ""  
  178. if(Test-Path -Path ("c:\temp\" + $MailboxName + "PullSubWM.wm")){ 
  179.     $psSub = Import-Csv -Path ("c:\temp\" + $MailboxName + "PullSubWM.wm") 
  180.     $request = GetEventsRequest -SubscriptionId $psSub.SubscriptionID -Watermark $psSub.Watermark -ImpersonationHeader $MailboxName 
  181.     $mbMailboxFolderURI = New-Object System.Uri($service.url)   
  182.     $wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)   
  183.     $wrWebRequest.CookieContainer =  New-Object System.Net.CookieContainer    
  184.     $wrWebRequest.KeepAlive = $false;   
  185.     $wrWebRequest.Useragent = "EWS Script" 
  186.     $wrWebRequest.Headers.Set("Pragma", "no-cache");   
  187.     $wrWebRequest.Headers.Set("Translate", "f");   
  188.     $wrWebRequest.Headers.Set("Depth", "0");   
  189.     $wrWebRequest.ContentType = "text/xml";   
  190.     $wrWebRequest.ContentLength = $expRequest.Length;   
  191.     $wrWebRequest.Timeout = 60000;   
  192.     $wrWebRequest.Method = "POST";   
  193.     $wrWebRequest.Credentials = $creds   
  194.     $bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($request);   
  195.     $wrWebRequest.ContentLength = $bqByteQuery.Length;   
  196.     $rsRequestStream = $wrWebRequest.GetRequestStream();   
  197.     $rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);   
  198.     $rsRequestStream.Close();   
  199.     $wrWebResponse = $wrWebRequest.GetResponse();   
  200.     $rsResponseStream = $wrWebResponse.GetResponseStream()   
  201.     $sr = new-object System.IO.StreamReader($rsResponseStream);   
  202.     $rdResponseDocument = New-Object System.Xml.XmlDocument   
  203.     $rdResponseDocument.LoadXml($sr.ReadToEnd()); 
  204.     $rdResponseDocument.Envelope.Body.GetEventsResponse.ResponseMessages.GetEventsResponseMessage.ResponseClass 
  205.     if($rdResponseDocument.Envelope.Body.GetEventsResponse.ResponseMessages.GetEventsResponseMessage.ResponseClass -eq "Error"){ 
  206.          
  207.         $rdResponseDocument.Envelope.Body.GetEventsResponse.ResponseMessages.GetEventsResponseMessage | fl 
  208.         Remove-Item ("c:\temp\" + $MailboxName + "PullSubWM.wm") 
  209.         Write-Host ("Removed old watermarkFile") 
  210.     } 
  211.     else{ 
  212.         if($rdResponseDocument.Envelope.Body.GetEventsResponse.ResponseMessages.GetEventsResponseMessage.ResponseClass -eq "Success"){ 
  213.             $pullSubSav = "" | Select Watermark,SubscriptionID 
  214.             $wmark2 = $rdResponseDocument.getElementsByTagName("t:Watermark")            
  215.             $pullSubSav.Watermark = $wmark2.Item(($wmark2.Count-1))."#text"  
  216.             $pullSubSav.SubscriptionID = $rdResponseDocument.Envelope.Body.GetEventsResponse.ResponseMessages.GetEventsResponseMessage.Notification.SubscriptionId  
  217.             $pullSubSav | Export-Csv -Path ("c:\temp\" + $MailboxName + "PullSubWM.wm") -NoTypeInformation 
  218.             Write-Host "Subscription saved" 
  219.             $movedEvents = $rdResponseDocument.getElementsByTagName("t:MovedEvent")  
  220.             if($movedEvents.Count -gt 0){ 
  221.                 try{ 
  222.                     for($intmc=0;$intmc -lt $movedEvents.Count;$intmc++){ 
  223.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service, $movedEvents.Item($intmc).ItemId.Id); 
  224.                         $ItemEvt = "" | Select EventTime,MessageDateTimeReceived,Subject,MovedFrom,MovedTo,LastModifiedName 
  225.                         $ItemEvt.EventTime = $movedEvents.Item($intmc).TimeStamp 
  226.                         Write-Host ("Processing : " + $item.Subject) 
  227.                         write-host ("Last Modified by :" + $item.LastModifiedName) 
  228.                         $ItemEvt.Subject = $item.Subject  
  229.                         $ItemEvt.LastModifiedName = $item.LastModifiedName 
  230.                         $ItemEvt.MessageDateTimeReceived = $item.DateTimeReceived        
  231.                                  
  232.                         #$movedEvents.Item($intmc).OldItemId.Id 
  233.                      
  234.                         if($FolderCollection.containsKey($movedEvents.Item($intmc).OldParentFolderId.Id)){ 
  235.                             Write-Host ("Moved From Folder " + $FolderCollection[$movedEvents.Item($intmc).OldParentFolderId.Id]) 
  236.                             $ItemEvt.MovedFrom = $FolderCollection[$movedEvents.Item($intmc).OldParentFolderId.Id] 
  237.                         }                    
  238.                         if($FolderCollection.containsKey($movedEvents.Item($intmc).ParentFolderId.Id)){ 
  239.                             Write-Host ("Moved To Folder " + $FolderCollection[$movedEvents.Item($intmc).ParentFolderId.Id]) 
  240.                             $ItemEvt.MovedTo = $FolderCollection[$movedEvents.Item($intmc).ParentFolderId.Id] 
  241.                         } 
  242.                         else{ 
  243.                              if ($movedEvents.Item($intmc).ParentFolderId.Id -eq $Deletions.Id.UniqueId) 
  244.                              { 
  245.                                 Write-Host ("Moved to Recoverable Items - Deleted Items");                           
  246.                              } 
  247.                              $ItemEvt.MovedTo = "Moved to Recoverable Items - Deleted Items" 
  248.                         } 
  249.                         Add-Content -Path $Script:changeLog ($ItemEvt.EventTime + ",`"" + $ItemEvt.MessageDateTimeReceived + "`",`"" + $ItemEvt.Subject + "`"," + $ItemEvt.MovedFrom + "," + $ItemEvt.MovedTo + "," + $ItemEvt.LastModifiedName) 
  250.                     } 
  251.                 } 
  252.                 catch{ 
  253.                     Write-Host ($Error | fl) 
  254.                     $Error.Clear() 
  255.                 } 
  256.             } 
  257.  
  258.         } 
  259.     }    
  260. } 
  261. else{ 
  262.     $InboxId = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)   
  263.     $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1   
  264.     $fldArray[0] = $InboxId   
  265.     $pullsub = $service.SubscribeToPullNotifications($fldArray,$duration, $WaterMark, $evEvents); 
  266.     $gEvents =  $pullsub.GetEvents(); 
  267.     $pullSubSav = "" | Select Watermark,SubscriptionID 
  268.     $pullSubSav.Watermark = $pullsub.Watermark 
  269.     $pullSubSav.SubscriptionID = $pullsub.Id 
  270.     $pullSubSav | Export-Csv -Path ("c:\temp\" + $MailboxName + "PullSubWM.wm") -NoTypeInformation 
  271.     Write-Host "Subscription saved"  
  272. }  



Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
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.