Friday, September 05, 2008

Deleting Items in a mailbox using Exchange Web Services and Powershell

This post continues on from my post a couple of weeks ago on digesting the quarantine mailbox in Exchange 2007. If you are digesting the quarantine mailbox one thing you might also want to automate is the purging of quarantined messages from the mailbox after a month if nothing has been done with them. Also if you have unmonitored mailboxes for auto-responses etc you might also want something that will delete messages that are older than a certain time period so to do this with EWS you need to look at first building a list of the itemIDs for the items you want to delete using a FindItem request and then batching your delete request for these items. For performance reasons its best to make sure that your batches that delete the items are a reasonable size to avoid performance issues on your CAS server.

The DeleteItem request in EWS is relatively straight forward to use but there are a few options you should be aware of. When you delete an item within the Exchange Store there are a couple of different types of deletes you can do. A Soft delete puts the item being deleted into the dumpster of the folder you’re deleting it from where its stays until the deleted item retention period expires. A Hard Delete removes the item completely meaning there’s is no hope of recovery. Then there is the normal Outlook/OWA client functionality which moves an item into the deleted items folder where its sits until a user empties their deleted items folder where its then put into the dumpster of the deleted items folder where its stays until the deleted item retention period expires. EWS caters for all these modes of operation via the EWS.DisposalType see

The other things to be aware of is if your deleting calendar items is you can control if calendar responses are sent to the meeting organizers and you can also control how recurring task deletes are handled. Because I’m focusing on Mail items I’ll leave these to the side.

So an EWS deleteitem request that would delete an array of itemid you pass into it and return a string that showed the results would look something like this

public String DeleteItems(BaseItemIdType[] idItemstoDelete,DisposalType diType) {

String rtReturnString = "";

DeleteItemType diDeleteItemRequest = new DeleteItemType();

diDeleteItemRequest.ItemIds = idItemstoDelete;

diDeleteItemRequest.DeleteType = diType;

diDeleteItemRequest.SendMeetingCancellationsSpecified = true;

diDeleteItemRequest.SendMeetingCancellations = CalendarItemCreateOrDeleteOperationType.SendToNone;

DeleteItemResponseType diResponse = esb.DeleteItem(diDeleteItemRequest);

ResponseMessageType[] diResponseMessages = diResponse.ResponseMessages.Items;

int DeleteSuccess = 0;

int DeleteError = 0;

foreach (ResponseMessageType repMessage in diResponseMessages)


if (repMessage.ResponseClass == ResponseClassType.Success) {



else {


Console.WriteLine("Error Occured");




rtReturnString = DeleteSuccess.ToString() + " Messages Deleted " + DeleteError + " Errors";

return rtReturnString;


What I’ve done is included this method into my Powershell EWS library so I can then use it with a couple of lines of script. To actually find the items to delete we need to use another existing method in the library that will return a generic list of items within a particular mailbox folder based on the items messsage class and a DateRange. So this allows us to write a script like the folloiwng to do a Soft Delete of any items within a mailbox where those Items where received during the duration that is specified (startdate is the earliist received time enddate is the datetime of the newest received item to delete). If you want to filter based on a particualar message class this can be achieve by modifying the following line eg a modification such as this would mean only NDR's would be deleted.

$msgList = $ewc.FindItems($fldarry, $drDuration, $null, "REPORT.IPM.Note.NDR")

To use this script you need my ewsutil library which you can download from

The script to do the delete looks like this a few thing to take note of is the date range of the items that will be deleted

$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow.AddDays(-365)
$drDuration.EndTime = [DateTime]::UtcNow.AddDays(-31)

And the type of delete its going to peform which is a soft delete.


The script seperates the deletes into batchs of 100 for performance reasons.

The script use my EWCConnection object which I’ve documented here it allows both impersonation and delegation authentication models.

With any script like this that performs deletes you should take that atmost of great care to ensure you have backups before running and that you have fully tested the process.

I’ve put a download of this script here the script itself looks like


$mbMailboxEmail = ""
$ewc = new-object EWSUtil.EWSConnection($mbMailboxEmail,$false, $null,$null,$null,$null)

$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow.AddDays(-365)
$drDuration.EndTime = [DateTime]::UtcNow.AddDays(-31)

$dTypeFld = new-object EWSUtil.EWS.DistinguishedFolderIdType
$dTypeFld.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::inbox

$mbMailbox = new-object EWSUtil.EWS.EmailAddressType
$mbMailbox.EmailAddress = $mbMailboxEmail
$dTypeFld.Mailbox = $mbMailbox

$fldarry = new-object EWSUtil.EWS.BaseFolderIdType[] 1
$fldarry[0] = $dTypeFld
$msgList = $ewc.FindItems($fldarry, $drDuration, $null, "")
$batchsize = 100
$bcount = 0
if ($msgList.Count -ne 0){
$itarry = new-object EWSUtil.EWS.ItemIdType[] $batchsize
for($ic=0;$ic -lt $msgList.Count;$ic++){
if ($bcount -ne $batchsize){
$itarry[$bcount] = $msgList[$ic].ItemId
$itarry = $null
$itarry = new-object EWSUtil.EWS.ItemIdType[] $batchsize
$bcount = 0
$itarry[$bcount] = $msgList[$ic].ItemId



Anonymous said...

how about deleting from Sync Issues folder? EWSUtil.EWS.DistinguishedFolderIdNameType does not have that as a valid name?

Anonymous said...

Hello, loading EWSUTIL in Windows 8 Powershell gives the following error, how can I resolve the issue?
Exception calling "LoadFile" with "1" argument(s): "An attempt was made to load an assembly from a network location
which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the
.NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to
sandbox the assembly, please enable the loadFromRemoteSources switch. See for more information."

Unknown said...

Good Morning
I need to run this script for Exchange 2010 enviroment but it seems that the scritp and tools has been delete.
Is there any way to get that script ?