Categories

Outlook: deleting mail items

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

function remove-mailitem {            
[CmdletBinding(SupportsShouldProcess=$true)]            
param (            
 [parameter(Mandatory=$true)]            
 [string]$mailfolder,            
              
 [datetime]$start,            
 [datetime]$finish            
)            
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")) {            
    $item.Delete()            
  }            
              
}            
               
}            
}


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")) {
  $item.Delete()
}



This adds another safety level to the function

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>