Skip to main content

Item Age Sample one reporting on the Item Count for different Date Ranges in Exchange using EWS and Powershell

This is sample 1 from the Item Age Section of my MEC talk, this sample uses an AQS query to look at the Item count for Items within a folder based on its age. The purpose of this script is to be able to show a quick Item count of particular folders based on the age of items eg this is the result of running it across all mailboxes on a server to look at the Item age of Inbox folders




This script uses an AQS range query eg "System.Message.DateReceived:01/01/2009..01/01/2010" would return the Items within a folder that has a RecievedDateTime between 2009 and 2010. Its also uses a ItemView with the page size of 1. This means the query should return in the shortest time possible but we still get the total number of Items that can be fullfiled by this query using the TotalCount property of the results set.

I've created two different versions of this script the first is a script you can just run on one mailbox eg

.\ItemCounts.ps1 mec@msgdevelop.onmicrosoft.com

The second version uses Get-Mailbox to report on all Mailboxes on a server it includes code that creates a remote powershell connection to server if one doesn't exist. 

The script looks at the Inbox by default if you want to change the folder it reports on you need to modify the following line

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
I've put a download of the two scripts here

The code for the second script looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. ## Load Managed API dll    
  4. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  5.     
  6. ## Set Exchange Version    
  7. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  8.     
  9. ## Create Exchange Service Object    
  10. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  11.     
  12. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  13.     
  14. #Credentials Option 1 using UPN for the windows Account    
  15. $psCred = Get-Credential    
  16. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  17. $service.Credentials = $creds        
  18.     
  19. #Credentials Option 2    
  20. #service.UseDefaultCredentials = $true    
  21.     
  22. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  23.     
  24. ## Code From http://poshcode.org/624  
  25. ## Create a compilation environment  
  26. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  27. $Compiler=$Provider.CreateCompiler()  
  28. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  29. $Params.GenerateExecutable=$False  
  30. $Params.GenerateInMemory=$True  
  31. $Params.IncludeDebugInformation=$False  
  32. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  33.   
  34. $TASource=@' 
  35.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  36.     public class TrustAll : System.Net.ICertificatePolicy { 
  37.       public TrustAll() {  
  38.       } 
  39.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  40.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  41.         System.Net.WebRequest req, int problem) { 
  42.         return true; 
  43.       } 
  44.     } 
  45.   } 
  46. '@   
  47. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  48. $TAAssembly=$TAResults.CompiledAssembly  
  49.   
  50. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  51. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  52. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  53.   
  54. ## end code from http://poshcode.org/624  
  55.     
  56. ## 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    
  57.     
  58. #CAS URL Option 1 Autodiscover    
  59.     
  60.      
  61. #CAS URL Option 2 Hardcoded    
  62.     
  63. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  64. #$service.Url = $uri      
  65.     
  66. ## Optional section for Exchange Impersonation    
  67.     
  68. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  69.   
  70. $Script:rptCollection = @()  
  71.   
  72. function getFolderItemCounts($MailboxName){  
  73.     "Processing Mailbox : " + $MailboxName  
  74.     if($service.url -eq $null){  
  75.         $service.AutodiscoverUrl($MailboxName,{$true})    
  76.         "Using CAS Server : " + $Service.url   
  77.     }  
  78.     # Bind to the Inbox Folder  
  79.     $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  80.     $Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  81.   
  82.     $rptObject = "" | Select MailboxName,FolderName,Olderthen2009,ItemCount2009,ItemCount2010,ItemCount2011,ItemCount2012  
  83.     $rptObject.MailboxName = $MailboxName  
  84.     $rptObject.FolderName = $Folder.DisplayName  
  85.     $AQSString = "System.Message.DateReceived:"   
  86.   
  87.     #Define ItemView to retrive just 1 Item      
  88.     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)    
  89.     $fiItems = $service.FindItems($Folder.Id,($AQSString + "<01/01/2009"),$ivItemView)  
  90.     "Older then 2009 Total Items : " + $fiItems.TotalCount  
  91.     $rptObject.Olderthen2009 = $fiItems.TotalCount  
  92.     $Range = "01/01/2009..01/01/2010"   
  93.     $fiItems = $service.FindItems($Folder.Id,($AQSString + $Range),$ivItemView)  
  94.     "2009 Total Items : " + $fiItems.TotalCount  
  95.     $rptObject.ItemCount2009 = $fiItems.TotalCount  
  96.     $Range = "01/01/2010..01/01/2011"   
  97.     $fiItems = $service.FindItems($Folder.Id,($AQSString + $Range),$ivItemView)  
  98.     "2010 Total Items : " + $fiItems.TotalCount  
  99.     $rptObject.ItemCount2010 = $fiItems.TotalCount  
  100.     $Range = "01/01/2011..01/01/2012"   
  101.     $fiItems = $service.FindItems($Folder.Id,($AQSString + $Range),$ivItemView)  
  102.     "2011 Total Items : " + $fiItems.TotalCount  
  103.     $rptObject.ItemCount2011 = $fiItems.TotalCount  
  104.     $Range = "01/01/2012..01/01/2013"   
  105.     $fiItems = $service.FindItems($Folder.Id,($AQSString + $Range),$ivItemView)  
  106.     $rptObject.ItemCount2012 = $fiItems.TotalCount  
  107.     "2012 Total Items : " + $fiItems.TotalCount  
  108.     $Script:rptCollection += $rptObject  
  109. }  
  110.   
  111. if((Get-PSSession | Where-Object {$_.ConfigurationName -eq "Microsoft.Exchange"}) -eq $null){  
  112.     $rpRemotePowershell = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -credential $psCred  -Authentication Basic -AllowRedirection    
  113.     $importresults = Import-PSSession $rpRemotePowershell   
  114. }  
  115. Get-Mailbox -ResultSize Unlimited | ForEach-Object{  
  116.     getFolderItemCounts($_.PrimarySMTPAddress)  
  117. }  
  118.   
  119. $tableStyle = @" 
  120. <style> 
  121. BODY{background-color:white;} 
  122. TABLE{border-width: 1px; 
  123.   border-style: solid; 
  124.   border-color: black; 
  125.   border-collapse: collapse; 
  126. } 
  127. TH{border-width: 1px; 
  128.   padding: 10px; 
  129.   border-style: solid; 
  130.   border-color: black; 
  131.   background-color:#66CCCC 
  132. } 
  133. TD{border-width: 1px; 
  134.   padding: 2px; 
  135.   border-style: solid; 
  136.   border-color: black; 
  137.   background-color:white 
  138. } 
  139. </style> 
  140. "@  
  141.     
  142. $body = @" 
  143. <p style="font-size:25px;family:calibri;color:#ff9100">  
  144. $TableHeader  
  145. </p>  
  146. "@  
  147.   
  148. $Script:rptCollection | ConvertTo-HTML -head $tableStyle –body $body | Out-File c:\temp\ItemCounts.htm  




Popular posts from this blog

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 Gr...

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You ...

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 ...
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.