Skip to main content

Exchange Attachment statistics reporting with EWS and Powershell

The following script is a combination of a couple of other scripts I've posted in the past, what it does is compiles statistics of the messages with and without attachments in a Mailbox and then produces a report. To do this in EWS you need to look at every Item in the mailbox,  if the item has attachments it determines how large these attachments are and keeps a running tab of the largest attachment in the mailbox. In Exchange there are a number of different attachment types but EWS divides them into two distinct types, File Attachments and ItemAttachment which are basically attached Exchange Items. This script compile statistics around these two distinct types but doesn't process down to the embeeded attachment level. The results of all the requests are added together to produce a final report that reflects the attachment statistics for the entire mailbox. A picture is worth a thousand words so it produces a report like


 To get the information about the Items in the Mailbox the FindItem Operation is used, however as FindItem doesn't return detailed information about attachments the LoadPropertiesForItems method is used which does a batch GetItem request on a collection of results. One thing to note is the AttachmentSize information isn't returned by EWS in Exchange 2007 so this script will only work for Exchange 2010 up.

This script will prompt for what security credentials you want to use and these creds need full access to the Mailboxes your scanning (an alternative would be to use Impersonation but that would require the script to be changed).

You need to feed the script with a CSV file like

smtpaddress
user1@domain.com
user2@domain.com

I've put a download of this script here  the script itself looks like.

  1. $Script:rptCollection = @()    
  2. ## Load Managed API dll    
  3. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  4.     
  5. ## Set Exchange Version    
  6. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  7.     
  8. ## Create Exchange Service Object    
  9. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  10.     
  11. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  12.     
  13. #Credentials Option 1 using UPN for the windows Account    
  14. $psCred = Get-Credential    
  15. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  16. $service.Credentials = $creds        
  17.     
  18. #Credentials Option 2    
  19. #service.UseDefaultCredentials = $true    
  20.     
  21. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  22.     
  23. ## Code From http://poshcode.org/624  
  24. ## Create a compilation environment  
  25. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  26. $Compiler=$Provider.CreateCompiler()  
  27. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  28. $Params.GenerateExecutable=$False  
  29. $Params.GenerateInMemory=$True  
  30. $Params.IncludeDebugInformation=$False  
  31. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  32.   
  33. $TASource=@' 
  34.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  35.     public class TrustAll : System.Net.ICertificatePolicy { 
  36.       public TrustAll() {  
  37.       } 
  38.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  39.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  40.         System.Net.WebRequest req, int problem) { 
  41.         return true; 
  42.       } 
  43.     } 
  44.   } 
  45. '@   
  46. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  47. $TAAssembly=$TAResults.CompiledAssembly  
  48.   
  49. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  50. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  51. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  52.   
  53. ## end code from http://poshcode.org/624  
  54.     
  55. ## 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    
  56.     
  57. #CAS URL Option 1 Autodiscover    
  58. #$service.AutodiscoverUrl($MailboxName,{$true})    
  59. #"Using CAS Server : " + $Service.url     
  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.   
  71. function Process-Mailbox{  
  72.     param (  
  73.             $SmtpAddress = "$( throw 'SMTPAddress is a mandatory Parameter' )"  
  74.           )  
  75.     process{  
  76.     $rptObj = "" | select MailboxName,TotalItem,TotalItemSize,TotalItemsNoAttach,TotalItemsNoAttachSize,TotalItemsAttach,TotalItemsAttachSize,TotalFileAttachments,TotalFileAttachmentsSize,TotalItemAttachments,TotalItemAttachmentsSize,LargestAttachmentSize,LargestAttachmentName  
  77.     $rptObj.MailboxName = $SmtpAddress  
  78.     $rptObj.TotalItem = 0  
  79.     $rptObj.TotalItemSize = [Int64]0  
  80.     $rptObj.TotalItemsNoAttach = 0  
  81.     $rptObj.TotalItemsNoAttachSize = [Int64]0  
  82.     $rptObj.TotalItemsAttach = 0  
  83.     $rptObj.TotalItemsAttachSize = [Int64]0  
  84.     $rptObj.TotalFileAttachments = 0  
  85.     $rptObj.TotalFileAttachmentsSize  = [Int64]0  
  86.     $rptObj.TotalItemAttachments = 0  
  87.     $rptObj.TotalItemAttachmentsSize  = [Int64]0  
  88.     $rptObj.LargestAttachmentSize = [Int64]0  
  89.     $rptObj.LargestAttachmentName = ""  
  90.     "Processing Mailbox : " + $SmtpAddress  
  91.       
  92.     #check Anchor header for Exchange 2013/Office365  
  93.     if($service.HttpHeaders.ContainsKey("X-AnchorMailbox")){  
  94.         $service.HttpHeaders["X-AnchorMailbox"] = $SmtpAddress  
  95.     }else{  
  96.         $service.HttpHeaders.Add("X-AnchorMailbox"$SmtpAddress);  
  97.     }  
  98.     "AnchorMailbox : " + $service.HttpHeaders["X-AnchorMailbox"]  
  99.     #Define ItemView to retrive just 1000 Items      
  100.     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  101.     $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)    
  102.     $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Size)  
  103.     $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)  
  104.     $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeCreated)  
  105.     $ivItemView.PropertySet = $psPropset  
  106.     $TotalSize = 0  
  107.     $TotalItemCount = 0  
  108.   
  109.   
  110.     #Define Function to convert String to FolderPath    
  111.     function ConvertToString($ipInputString){    
  112.         $Val1Text = ""    
  113.         for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){    
  114.                 $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))    
  115.                 $clInt++    
  116.         }    
  117.         return $Val1Text    
  118.     }   
  119.   
  120.     #Define Extended properties    
  121.     $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  122.     $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$SmtpAddress)    
  123.     #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling    
  124.     $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  125.     #Deep Transval will ensure all folders in the search path are returned    
  126.     $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  127.     $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  128.     $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);    
  129.     #Add Properties to the  Property Set    
  130.     $psPropertySet.Add($PR_Folder_Path);    
  131.     $fvFolderView.PropertySet = $psPropertySet;    
  132.     #The Search filter will exclude any Search Folders    
  133.     $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  134.     $fiResult = $null    
  135.     #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox    
  136.     do {    
  137.         $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilter,$fvFolderView)    
  138.         foreach($ffFolder in $fiResult.Folders){    
  139.             $foldpathval = $null    
  140.             #Try to get the FolderPath Value and then covert it to a usable String     
  141.             if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))    
  142.             {    
  143.                 $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)    
  144.                 $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }    
  145.                 $hexString = $hexArr -join ''    
  146.                 $hexString = $hexString.Replace("FEFF""5C00")    
  147.                 $fpath = ConvertToString($hexString)    
  148.             }    
  149.               
  150.             $totalItemCnt = 1  
  151.             if($ffFolder.TotalCount -ne $null){  
  152.                 $totalItemCnt = $ffFolder.TotalCount  
  153.                 "Processing FolderPath : " + $fpath  + " Item Count " + $totalItemCnt  
  154.             }  
  155.             else{  
  156.                 "Processing FolderPath : " + $fpath  
  157.             }  
  158.             if($totalItemCnt -gt 0){  
  159.                 #Define ItemView to retrive just 1000 Items      
  160.                 $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  161.                 $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)    
  162.                 $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Size)  
  163.                 $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)  
  164.                 $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeCreated)  
  165.                 $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments)  
  166.                 $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments)  
  167.                 $fipsPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)    
  168.                 $ivItemView.PropertySet = $fipsPropset        
  169.                 $fiItems = $null      
  170.                 do{      
  171.                     $fiItems = $service.FindItems($ffFolder.Id,$ivItemView)   
  172.                     if($fiItems.Items.Count -gt 0){  
  173.                         [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)   
  174.                         "processing : " + $fiItems.Items.Count + " Items"  
  175.                         foreach($Item in $fiItems.Items){  
  176.                             $rptObj.TotalItem +=1  
  177.                             $rptObj.TotalItemSize += [Int64]$Item.Size  
  178.                             if($Item.Attachments.Count -gt 0){  
  179.                                 $rptObj.TotalItemsAttach +=1  
  180.                                 $rptObj.TotalItemsAttachSize += [Int64]$Item.Size  
  181.                                 foreach($Attachment in $Item.Attachments){                            
  182.                                     if($Attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment]){  
  183.                                         $rptObj.TotalFileAttachments +=1  
  184.                                         $rptObj.TotalFileAttachmentsSize += $Attachment.Size  
  185.                                         $attachSize = [Math]::Round($Attachment.Size/1MB,2)  
  186.                                         if($attachSize -gt $rptobj.LargestAttachmentSize){  
  187.                                             $rptobj.LargestAttachmentSize = $attachSize  
  188.                                             $rptobj.LargestAttachmentName = $Attachment.Name  
  189.                                         }  
  190.                                     }  
  191.                                     else{  
  192.                                         $rptObj.TotalItemAttachments +=1  
  193.                                         $rptObj.TotalItemAttachmentsSize += $Attachment.Size  
  194.                                     }  
  195.                                 }  
  196.                             }  
  197.                             else{  
  198.                                 $rptObj.TotalItemsNoAttach +=1  
  199.                                 $rptObj.TotalItemsNoAttachSize += [Int64]$Item.Size  
  200.                             }  
  201.                         }  
  202.                     }      
  203.                     $ivItemView.Offset += $fiItems.Items.Count      
  204.                 }while($fiItems.MoreAvailable -eq $true)  
  205.             }  
  206.         }   
  207.         $fvFolderView.Offset += $fiResult.Folders.Count  
  208.     }while($fiResult.MoreAvailable -eq $true)  
  209.     #convert Sizes to MB  
  210.   
  211.     if($rptObj.TotalItemSize -ne 0){  
  212.         $rptObj.TotalItemSize = [Math]::Round($rptObj.TotalItemSize/1MB)  
  213.     }  
  214.     if($rptObj.TotalItemsNoAttachSize -ne 0){  
  215.         $rptObj.TotalItemsNoAttachSize = [Math]::Round($rptObj.TotalItemsNoAttachSize/1MB)  
  216.     }  
  217.     if($rptObj.TotalItemsAttachSize -ne 0){  
  218.         $rptObj.TotalItemsAttachSize = [Math]::Round($rptObj.TotalItemsAttachSize/1MB)  
  219.     }  
  220.     if($rptObj.TotalFileAttachmentsSize -ne 0){  
  221.         $rptObj.TotalFileAttachmentsSize = [Math]::Round($rptObj.TotalFileAttachmentsSize/1MB)  
  222.     }  
  223.     if($rptObj.TotalItemAttachmentsSize -ne 0){  
  224.         $rptObj.TotalItemAttachmentsSize = [Math]::Round($rptObj.TotalItemAttachmentsSize/1MB)  
  225.     }  
  226.     $Script:rptCollection += $rptObj  
  227.     }  
  228. }  
  229.   
  230. Import-Csv -Path $args[0] | ForEach-Object{  
  231.     if($service.url -eq $null){  
  232.         $service.AutodiscoverUrl($_.SmtpAddress,{$true})   
  233.         "Using CAS Server : " + $Service.url   
  234.     }  
  235.     Try{  
  236.         Process-Mailbox -SmtpAddress $_.SmtpAddress  
  237.     }  
  238.     catch{  
  239.         LogWrite("Error processing Mailbox : " + $_.SmtpAddress + $_.Exception.Message.ToString())  
  240.     }  
  241. }  
  242. $Script:rptCollection | Export-Csv -NoTypeInformation -Path c:\temp\mbAttachReport.csv  




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 Graph is limited to a m

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 need to authorize it in you tenant (eg build a small ap

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.