header image

Outlook: deleting mail items

Posted by: | August 4, 2011 | No Comment |

As promised here is the function to delete mail items in a specific folder

function remove-mailitem {            
param (            
if ($start -and $finish){            
  if ($start -ge $finish){Throw "Finish $($finish) before Start $($start)"}            
$outlook = New-Object -ComObject Outlook.Application            
$folders | where {$_.Path -like "*$mailfolder"} |            
foreach {            
$targetfolder = $outlook.Session.GetFolderFromID($_.EntryID, $_.StoreID)            
foreach ($item in $targetfolder.Items)  {            
 if ($start){if ($item.SentOn -lt $start){continue}}            
 if ($finish){if ($item.SentOn -gt $finish){continue}}            
  if ($psCmdlet.ShouldProcess("$($item.Subject) $($item.SentOn)", "deleting")) {            

If you’ve been following this series you will recognise how this works. The parameters are the mail folder and an optional start and finish date. A quick check to see if the dates are the right way round and we jump into the processing. The folders that match our input are selected and foreach of them we loop through the mail items.

The SentOn date is compared to the start and finish dates if they are defined. The item is skipped if it falls outside of those dates.

We can then delete the item. I’ve also added the –whatif parameter to the function by using   [CmdletBinding(SupportsShouldProcess=$true)] and

if ($psCmdlet.ShouldProcess("$($item.Subject) $($item.SentOn)", "deleting")) {



This adds another safety level to the function

under: Office 2010, Outlook, PowerShellV2, Windows 7