EWS Script: Move email items based on received date into a folder

Scenario:  You want to move email items based on date range into a folder.

Script:  The script performs the following:

  1. Attaches to the mailbox specified in the script
  2. Looks in the inbox for email items with a received that lies between a date range.
  3. Creates a folder
  4. Moves those items into that folder.
#Make sure the account you run this as has full access permissions to the mailbox

#Load the EWS Assembly
    Import-Module -Name "C:Program FilesMicrosoftExchange ServerV15BinMicrosoft.Exchange.WebServices.dll"

    $service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.Exchangeversion]::exchange2013)

    $service.Url = new-object System.Uri("https://Ex2013Srv1/EWS/Exchange.asmx")

#Define your Variables
    #$StartDate = [system.DateTime]::Today.AddDays(-1)
    #$EndDate = [system.DateTime]::Today
    [datetime]$StartDate  = "11/17/2015"
    [datetime]$EndDate = "11/18/2015"
    $mailboxname = "steve@domain.com"

#Bind your Folder & Create your filter
    $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    $Sfgt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $StartDate)
    $Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsLessThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $EndDate)

#Create Collection and Apply your Filter
    $sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
    $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(2000)
    $frFolderResult = $InboxFolder.FindItems($sfCollection,$view)

#Creates a Folder
    $NewFolder = new-object Microsoft.Exchange.WebServices.Data.Folder($service)
    $NewFolder.DisplayName = $EndDate.ToString("yyyy-MM-dd")

#Moves your Email Items
    foreach ($miMailItems in $frFolderResult.Items){
    "Moving:" + $miMailItems.Subject.ToString()


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: