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

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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

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.