Tuesday, October 02, 2012

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  




6 comments:

Anonymous said...

Is there a way to leverage this script to also include the total mailbox size for the date range? Ultimately the objective is to create an Ex2K10 Org wide mailbox database size report for all databases based on date range. Thank you. MM

Anonymous said...

Is there a way to do this on all mailboxes? It asks for credentials and when I put mind in, it just does my mailbox. I need to report sizes by date for the entire Exchange server.

Glen Scales said...

There are two different version of the script one use Get-Mailbox to retrieve the mailboxes to run against. Ultimately you will need rights on the Mailboxes you want to run it against or use EWS Impersonation.

Cheers
Glen

Unknown said...

You need Managed API dll to run this?

Daniel Dimitrov said...

Hello Greg,
I am so happy I found this script - it does half of what I need.
I need to run a report for all the mailboxes and return the following for each one - MailboxPrimarySMTPAddress, "2015 Total Items", "2015 Total Size", "2016 Total Items", "2016 Total Size".
I tried adding

"2015 Total Size : " + $fiItems.TotalSize

But it returns nothing.
I have checked all the members/properties for $ivItemView but I couldn't figure out how you get TotalCount, so I can get TotalSize.
And I need to make sure those values get into the HTML report too.
I also tried to use your other script GetItemAgeFromItemsInFolder.ps1 but got lost there too - I will need to enumerate all the folders in each mailbox, then aggregate the size per year, then output only the data for 2015 and 2016.

I hope you monitor this blog post and would have the time to help me get the additional functionality working.

Thank you in advance!


Daniel

Glen Scales said...

I would suggest you look at http://gsexdev.blogspot.com.au/2016/04/ews-basics-reporting-on-age-of-items-in.html instead and customize that version