Skip to main content

Cleaning up and Reporting on Items based on the Subject on Exchange using a EWS search with Powershell

If your unaware there is nasty mass mailer virus outbreak at the moment if you haven't already i would strongly urge you to visit and implement the measures in http://social.technet.microsoft.com/wiki/contents/articles/worm-win32-visal-b.aspx

The above gives the best and quickest method for cleaning the affects of an outbreak using the EMS export-mailbox cmdlet but i thought I'd give some alternate methods using EWS . I can't guarantee any of these methods like i would with Export-mailbox and I would expect them to be slower (and possibly very slow) but they may come in use especially if your access is limited but you can use EWS Impersonation or if you looking to do some reporting based on subject.

Finding Items based on there Subject is relatively simple in EWS and involves the use of a Search filter or if your lucky enough to be using Exchange 2010 you can make use of AQS which I blogged about earlier here . With a virus outbreak they generally start on a particular date so it makes sense to make your query more efficient by only searching for items that where received in the last 7 days. So a search filter for 2007 would look like

$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject, $subjecttoSearch)
$Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $MailDate)
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($Sfir)


The AQS query for the same thing would look like AQSQuery = "Received:this week AND subject:`"" + $subjecttoSearch + "`"" . There is one very important catch with the AQS query is that it will do a exact phrase match but not a exact subject match. So for example if you where trying to match the phrase "here you have" in the subject it would also match "here you have a example of" there are different operators that you can use in AQS but not one that i could find that would do a exact property match(I anybody finds an AQS query that works (emphasis on works rather then should work based on the documentation) please let me know). To get around this and also as a double check before you delete anything a simple logic if statement can be used in your code.

When it comes to deleting Items in the EWS Managed API you can use the Delete method of the Item object which would basically call a deleteItem operation each time you called this method or a faster method is create an array of itemid's that you would like deleted and then use the batch deleteItems method which is the method I've used.

The scripts are setup to use Delegation but if you want to use impersonation instead just add the following line

$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)

Because searching like this is not only usefully for deleting Items but for also reporting on things I've created a reporting version of the scripts as well that just emails a html report of a what it finds within a mailbox and includes the transport headers of the messages in question. The script I've created does a deep traversal to get the folderid details and then a single finditems on each folder the 2007 version using searchfilters and the 2010 version use AQS.

The delete scripts do a SoftDelete meaning the item goes into the dumpster of the folder it was deleted from (you could make this a hard delete).

Before using these script you need to customize the following variable with the subject you want to search for the example I've used is I hate spam

$subjecttoSearch = "I hate Spam"

You also need to set the mailbox name to run against or change it to $arg[0] and run the script with a cmdline argument. In the reporting script the To,From and SMTP server needs to be set.

I've put a download of all 4 scripts here the 2007 delete version looks like.

$MailboxName = "user@mailbox.com"

$subjecttoSearch = "I hate Spam"
$MailDate = [system.DateTime]::Now.AddDays(-7)

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)

$deleteMode = [Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete
$aptcancelMode = [Microsoft.Exchange.WebServices.Data.SendCancellationsMode]::SendToNone
$taskmode = [Microsoft.Exchange.WebServices.Data.AffectedTaskOccurrence]::AllOccurrences

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$rfRootFolderID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)
$rfRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$rfRootFolderID)
$fvFolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000);
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
$fvFolderView.PropertySet = $Propset
$ffResponse = $rfRootFolder.FindFolders($fvFolderView);

foreach ($ffFolder in $ffResponse.Folders){
"Checking " + $ffFolder.DisplayName
$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject, $subjecttoSearch)
$Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $MailDate)
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($Sfir)
$sfCollection.add($Sflt)
$ivview = new-object Microsoft.Exchange.WebServices.Data.ItemView(20000)
$frFolderResult = $ffFolder.FindItems($sfCollection,$ivview)
$Itembatch = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.ItemId]))
foreach ($miMailItems in $frFolderResult.Items){
if ($miMailItems.Subject -eq $subjecttoSearch){
"****** Found" + $miMailItems.Subject
$Itembatch.add($miMailItems.Id)
}
}
"Number of Items found in folder : " + $Itembatch.Count
if($Itembatch.Count -ne 0){
"Deleting " + $Itembatch.Count + " Items"
$DelResponse = $service.DeleteItems($Itembatch,$deleteMode,$aptcancelMode,$taskmode)
foreach ($dr in $DelResponse) {
$dr.Result
}
}

}







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 Gr...

EWS-FAI Module for browsing and updating Exchange Folder Associated Items from PowerShell

Folder Associated Items are hidden Items in Exchange Mailbox folders that are commonly used to hold configuration settings for various Mailbox Clients and services that use Mailboxes. Some common examples of FAI's are Categories,OWA Signatures and WorkHours there is some more detailed documentation in the https://msdn.microsoft.com/en-us/library/cc463899(v=exchg.80).aspx protocol document. In EWS these configuration items can be accessed via the UserConfiguration operation https://msdn.microsoft.com/en-us/library/office/dd899439(v=exchg.150).aspx which will give you access to either the RoamingDictionary, XMLStream or BinaryStream data properties that holds the configuration depending on what type of FAI data is being stored. I've written a number of scripts over the years that target particular FAI's (eg this one that reads the workhours  http://gsexdev.blogspot.com.au/2015/11/finding-timezone-being-used-in-mailbox.html is a good example ) but I didn't have a gene...

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.