Friday, September 10, 2010

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
}
}

}