Skip to main content

Unread email ews Powershell Module with reply and forward counting

I've done a few of these Unread / Unused mailbox scripts over the years but this one has a bit of a difference. As well as counting the Total number of unread email in the Inbox over a certain period of time it uses the PidTagLastVerbExecuted property to count how many email messages over that period of time had the client action ReplytoSender, ReplyAll or forwarded and also the number of email in the SentItems folder. This property is set on messages in the Inbox message when one of those actions is taken by the client so it is useful for tracking the use of Mailboxes and gathering statistics around how they are being used. eg here are a few samples of running this module



The code uses both EWS and the Exchange Management Shell to get information about the Mailbox so you need to run it from within the EMS or a Remote PowerShell session (see this if your running it from Office365). I've put the script up on GitHub or you can download it from here. I've also created a Search Filter version of the code, this would work on Exchange 2007 and also if you have an issue where you only see a maximum of 250 items (which is an AQS bug in some version of Exchange) this will address this issue this is also on gihub here


The code itself looks like

function Connect-Exchange{ 
    param( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [string]$url
    )  
  Begin
   {
  Load-EWSManagedAPI
  
  ## Set Exchange Version  
  $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1
    
  ## Create Exchange Service Object  
  $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
    
  ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
    
  #Credentials Option 1 using UPN for the windows Account  
  #$psCred = Get-Credential  
  $creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
  $service.Credentials = $creds      
  #Credentials Option 2  
  #service.UseDefaultCredentials = $true  
   #$service.TraceEnabled = $true
  ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
    
  Handle-SSL 
    
  ## 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  
    
  #CAS URL Option 1 Autodiscover  
  if($url){
   $uri=[system.URI] $url
   $service.Url = $uri    
  }
  else{
   $service.AutodiscoverUrl($MailboxName,{$true})  
  }
  Write-host ("Using CAS Server : " + $Service.url)   
     
  #CAS URL Option 2 Hardcoded  
    
  #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
  #$service.Url = $uri    
    
  ## Optional section for Exchange Impersonation  
    
  #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  if(!$service.URL){
   throw "Error connecting to EWS"
  }
  else
  {  
   return $service
  }
 }
}

function Load-EWSManagedAPI{
    param( 
    )  
  Begin
 {
  ## Load Managed API dll  
  ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
  $EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
  if (Test-Path $EWSDLL)
      {
      Import-Module $EWSDLL
      }
  else
      {
      "$(get-date -format yyyyMMddHHmmss):"
      "This script requires the EWS Managed API 1.2 or later."
      "Please download and install the current version of the EWS Managed API from"
      "http://go.microsoft.com/fwlink/?LinkId=255472"
      ""
      "Exiting Script."
      exit
      } 
   }
}

function Handle-SSL{
    param( 
    )  
  Begin
 {
  ## Code From http://poshcode.org/624
  ## Create a compilation environment
  $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
  $Compiler=$Provider.CreateCompiler()
  $Params=New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.GenerateExecutable=$False
  $Params.GenerateInMemory=$True
  $Params.IncludeDebugInformation=$False
  $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
  $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
  $TAAssembly=$TAResults.CompiledAssembly

  ## We now create an instance of the TrustAll and attach it to the ServicePointManager
  $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
  [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

  ## end code from http://poshcode.org/624

 }
}

function CovertBitValue($String){  
    $numItempattern = '(?=\().*(?=bytes)'  
    $matchedItemsNumber = [regex]::matches($String, $numItempattern)   
    $Mb = [INT64]$matchedItemsNumber[0].Value.Replace("(","").Replace(",","")  
    return [math]::round($Mb/1048576,0)  
}  

function Get-UnReadMessageCount{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
  [Parameter(Position=4, Mandatory=$true)] [Int32]$Months
    )  
  Begin
 {
  $eval1 = "Last" + $Months + "MonthsTotal"
  $eval2 = "Last" + $Months + "MonthsUnread"
  $eval3 = "Last" + $Months + "MonthsSent"
  $eval4 = "Last" + $Months + "MonthsReplyToSender"
  $eval5 = "Last" + $Months + "MonthsReplyToAll"
  $eval6 = "Last" + $Months + "MonthForward"
  $reply = 0;
  $replyall = 0
  $forward = 0
  $rptObj = "" | select  MailboxName,Mailboxsize,LastLogon,LastLogonAccount,$eval1,$eval2,$eval4,$eval5,$eval6,LastMailRecieved,$eval3,LastMailSent  
  $rptObj.MailboxName = $MailboxName  
  if($url){
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials -url $url 
  }
  else{
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
  }
  if($useImpersonation.IsPresent){
   $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  }
  $AQSString1 = "System.Message.DateReceived:>" + [system.DateTime]::Now.AddMonths(-$Months).ToString("yyyy-MM-dd")   
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)     
  $SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)    
  $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)  
  $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)  
  $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)
  $psPropset.Add([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead)
  $PidTagLastVerbExecuted = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x1081,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer); 
  $psPropset.Add($PidTagLastVerbExecuted)
  $ivItemView.PropertySet = $psPropset
    $MailboxStats = Get-MailboxStatistics $MailboxName  
  $ts = CovertBitValue($MailboxStats.TotalItemSize.ToString())  
  write-host ("Total Size : " + $MailboxStats.TotalItemSize) 
     $rptObj.MailboxSize = $ts  
  write-host ("Last Logon Time : " + $MailboxStats.LastLogonTime) 
  $rptObj.LastLogon = $MailboxStats.LastLogonTime  
  write-host ("Last Logon Account : " + $MailboxStats.LastLoggedOnUserAccount ) 
  $rptObj.LastLogonAccount = $MailboxStats.LastLoggedOnUserAccount  
  $fiItems = $null
  $unreadCount = 0
  $settc = $true
     do{ 
   $fiItems = $Inbox.findItems($AQSString1,$ivItemView)  
   if($settc){
    $rptObj.$eval1 = $fiItems.TotalCount  
    write-host ("Last " + $Months + " Months : " + $fiItems.TotalCount)
    if($fiItems.TotalCount -gt 0){  
        write-host ("Last Mail Recieved : " + $fiItems.Items[0].DateTimeReceived ) 
        $rptObj.LastMailRecieved = $fiItems.Items[0].DateTimeReceived  
    }      
    $settc = $false
   }
       foreach($Item in $fiItems.Items){
     $unReadVal = $null
     if($Item.TryGetProperty([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead,[ref]$unReadVal)){
      if(!$unReadVal){
       $unreadCount++
      }
     } 
       $lastVerb = $null
     if($Item.TryGetProperty($PidTagLastVerbExecuted,[ref]$lastVerb)){
      switch($lastVerb){
       102 { $reply++ }
       103 { $replyall++}
       104 { $forward++}
      }
     } 
       }    
       $ivItemView.Offset += $fiItems.Items.Count    
   }while($fiItems.MoreAvailable -eq $true) 

  write-host ("Last " + $Months + " Months Unread : " + $unreadCount ) 
  $rptObj.$eval2 = $unreadCount  
  $rptObj.$eval4 = $reply
  $rptObj.$eval5 = $replyall
  $rptObj.$eval6 = $forward
  $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)  
  $fiResults = $SentItems.findItems($AQSString1,$ivItemView)  
  write-host ("Last " + $Months + " Months Sent : " + $fiResults.TotalCount  )
  $rptObj.$eval3 = $fiResults.TotalCount  
  if($fiResults.TotalCount -gt 0){  
      write-host ("Last Mail Sent Date : " + $fiResults.Items[0].DateTimeSent  )
      $rptObj.LastMailSent = $fiResults.Items[0].DateTimeSent  
  }  
  Write-Output $rptObj  
 }
}

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.