jhorsman
1/6/2018 - 10:23 AM

Start the year with a fresh, empty mailbox. This scripts moves emails from the Inbox (default folder) in a date range to another folder.

Start the year with a fresh, empty mailbox. This scripts moves emails from the Inbox (default folder) in a date range to another folder.

<#
 Start the year with a fresh, empty mailbox.
 This scripts moves emails from the Inbox (default folder) in a date range to another folder.
 
 Set $filterFromDate and $filterToDate to select the date range of mails to move.
 Set $tagetFolderName to the folder to move the mails to.

 Inspired by https://social.technet.microsoft.com/Forums/scriptcenter/en-US/5dc36dec-f88f-4e2d-8cba-385b6204ef6c/powershell-and-outlook-moving-messages?forum=ITCG
 and https://msdn.microsoft.com/en-us/magazine/dn189202.aspx
#>

$accountName = 'me@mail.com'
$filterFromDate = "[ReceivedTime] >= '#01/01/2017#'"
$filterToDate = "[ReceivedTime] < '#01/01/2018#'"
$targetFolderName = "Last year"


$ErrorActionPreference = "Stop"
Add-Type -AssemblyName microsoft.office.interop.outlook
$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $Outlook.GetNameSpace("mapi")

$inboxFolder = $namespace.getDefaultFolder($olFolders::olFolderInbox)
$MoveTarget = $namespace.Folders.Item($accountName).Folders.Item($targetFolderName)

$messages = $inboxFolder.Items.Restrict($filterFromDate).Restrict($filterToDate)
$totalCount = $messages.count
Write-Host ("Found {0} messages" -f $totalCount)

for ($inc = $totalCount; $inc -gt 0 ; $inc --) {
    $message = $messages.Item($inc)
    Write-Host ("{0}/{1}  {2}  {3}" -f ($totalCount - $inc + 1), $totalCount, $message.ReceivedTime, $message.Subject)
    [void] $message.Move($MoveTarget)
}