Unread e-mail ews Powershell Module with reply and ahead counting

Unread e-mail ews Powershell Module with reply and ahead counting I’ve accomplished a number of of those Unread / Unused mailbox scripts over time however this one has a little bit of a distinction. In addition to counting the Complete variety of unread e-mail within the Inbox over a sure time frame it makes use of the PidTagLastVerbExecuted property to rely what number of e-mail messages over that time frame had the shopper motion ReplytoSender, ReplyAll or forwarded and additionally the variety of e-mail within the SentItems folder. This property is about on messages within the Inbox message when a type of actions is taken by the shopper so it’s helpful for monitoring the usage of Mailboxes and gathering statistics round how they’re getting used. eg listed below are a few samples of working this module

The code makes use of each EWS and the Change Administration Shell to get details about the Mailbox so you’ll want to run it from throughout the EMS or a Distant PowerShell session (see this in case your working it from Workplace365). I’ve put the script up on GitHub or you may download it from right here. I’ve additionally created a Search Filter model of the code, this is able to work on Change 2007 and likewise when you have a difficulty the place you solely see a most of 250 gadgets (which is an AQS bug in some model of Change) it will deal with this situation that is additionally on gihub right here

The code itself seems like

operate Join-Change{ 
param(
[Parameter(Place=0, Obligatory=$true)] [string]$MailboxName,
[Parameter(Place=1, Obligatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
[Parameter(Place=2, Obligatory=$false)] [string]$url
)
Start
{
Load-EWSManagedAPI

## Set Change Model
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Change2013_SP1

## Create Change Service Object
$service = New-Object Microsoft.Change.WebServices.Knowledge.ExchangeService($ExchangeVersion)

## Set Credentials to make use of two choices are availible Option1 to make use of explict credentials or Possibility 2 use the Default (logged On) credentials

#Credentials Possibility 1 utilizing UPN for the home windows Account
#$psCred = Get-Credential
$creds = New-Object System.Web.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())
$service.Credentials = $creds
#Credentials Possibility 2
#service.UseDefaultCredentials = $true
#$service.TraceEnabled = $true
## Select to disregard any SSL Warning points brought on by Self Signed Certificates

Deal with-SSL

## Set the URL of the CAS (Shopper Entry Server) to make use of two choices are availbe to make use of Autodiscover to search out the CAS URL or Hardcode the CAS to make use of

#CAS URL Possibility 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 Possibility 2 Hardcoded

#$uri=[system.URI] "https://casservername/ews/exchange.asmx"
#$service.Url = $uri

## Elective part for Change Impersonation

#$service.ImpersonatedUserId = new-object Microsoft.Change.WebServices.Knowledge.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
if(!$service.URL){
throw "Error connecting to EWS"
}
else
{
return $service
}
}
}

operate Load-EWSManagedAPI{
param(
)
Start
{
## 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_MACHINESOFTWAREMicrosoftExchangeWeb Companies'|Kind-Object Title -Descending| Choose-Object -First 1 -ExpandProperty Title)).'Set up Listing') + "Microsoft.Exchange.WebServices.dll")
if (Take a look at-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
}
}
}

operate Deal with-SSL{
param(
)
Start
{
## Code From http://poshcode.org/624
## Create a compilation setting
$Supplier=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Supplier.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 Native.ToolkitExtensions.Web.CertificatePolicy{
public class TrustAll : System.Web.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Web.ServicePoint sp,
System.Safety.Cryptography.X509Certificates.X509Certificates cert,
System.Web.WebRequest req, int downside) {
return true;
}
}
}
'@
$TAResults=$Supplier.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly

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

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

}
}

operate CovertBitValue($String){
$numItempattern = '(?=().*(?=bytes)'
$matchedItemsNumber = [regex]::matches($String, $numItempattern)
$Mb = [INT64]$matchedItemsNumber[0].Worth.Exchange("(","").Exchange(",","")
return [math]::spherical($Mb/1048576,0)
}

operate Get-UnReadMessageCount{
param(
[Parameter(Place=0, Obligatory=$true)] [string]$MailboxName,
[Parameter(Place=1, Obligatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
[Parameter(Place=2, Obligatory=$false)] [switch]$useImpersonation,
[Parameter(Place=3, Obligatory=$false)] [string]$url,
[Parameter(Place=4, Obligatory=$true)] [Int32]$Months
)
Start
{
$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
$ahead = 0
$rptObj = "" | choose MailboxName,Mailboxsize,LastLogon,LastLogonAccount,$eval1,$eval2,$eval4,$eval5,$eval6,LastMailRecieved,$eval3,LastMailSent
$rptObj.MailboxName = $MailboxName
if($url){
$service = Join-Change -MailboxName $MailboxName -Credentials $Credentials -url $url
}
else{
$service = Join-Change -MailboxName $MailboxName -Credentials $Credentials
}
if($useImpersonation.IsPresent){
$service.ImpersonatedUserId = new-object Microsoft.Change.WebServices.Knowledge.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.Change.WebServices.Knowledge.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$folderid= new-object Microsoft.Change.WebServices.Knowledge.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)
$SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$ivItemView = New-Object Microsoft.Change.WebServices.Knowledge.ItemView(1000)
$psPropset= new-object Microsoft.Change.WebServices.Knowledge.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.Change.WebServices.Knowledge.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.Objects[0].DateTimeReceived )
$rptObj.LastMailRecieved = $fiItems.Objects[0].DateTimeReceived
}
$settc = $false
}
foreach($Merchandise in $fiItems.Objects){
$unReadVal = $null
if($Merchandise.TryGetProperty([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead,[ref]$unReadVal)){
if(!$unReadVal){
$unreadCount++
}
}
$lastVerb = $null
if($Merchandise.TryGetProperty($PidTagLastVerbExecuted,[ref]$lastVerb)){
swap($lastVerb){
102 { $reply++ }
103 { $replyall++}
104 { $ahead++}
}
}
}
$ivItemView.Offset += $fiItems.Objects.Rely
}whereas($fiItems.MoreAvailable -eq $true)

write-host ("Last " + $Months + " Months Unread : " + $unreadCount )
$rptObj.$eval2 = $unreadCount
$rptObj.$eval4 = $reply
$rptObj.$eval5 = $replyall
$rptObj.$eval6 = $ahead
$ivItemView = New-Object Microsoft.Change.WebServices.Knowledge.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.Objects[0].DateTimeSent )
$rptObj.LastMailSent = $fiResults.Objects[0].DateTimeSent
}
Write-Output $rptObj
}
}

Leave a Reply