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

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...

Downloading a shared file from Onedrive for business using Powershell

I thought I'd quickly share this script I came up with to download a file that was shared using One Drive for Business (which is SharePoint under the covers) with Powershell. The following script takes a OneDrive for business URL which would look like https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filename.txt This script is pretty simple it uses the SharePoint CSOM (Client side object Model) which it loads in the first line. It uses the URI object to separate the host and relative URL which the CSOM requires and also the SharePointOnlineCredentials object to handle the Office365 SharePoint online authentication. The following script is a function that take the OneDrive URL, Credentials for Office365 and path you want to download the file to and downloads the file. eg to run the script you would use something like ./spdownload.ps1 ' https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filen...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.
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.