Categories

Emptying the Deleted Items Folder

Continuing our look at scripting against Outlook & the hotmail connector

Many of the emails I get end up being read once and deleted. This leaves a ton of stuff in the deleted items folders. Periodically I’ll clean these up. This is one way how it can be accomplished.

function clear-deletedmail {            
            
$outlook = New-Object -ComObject Outlook.Application            
foreach ($folder in $outlook.Session.Folders){            
              
  foreach($mailfolder in $folder.Folders ) {            
    if ($mailfolder.Name -eq "Deleted Items" -and $mailfolder.Items.Count -gt 0){            
      foreach ($item in $mailfolder.Items){$item.Delete()}            
    }               
  }             
}            
}


All I’m doing is looping through my top level folders (email accounts) and for each of them finding a folder called Deleted Items.  If it has any content I will delete it.  Notice that the deletions have to occur on the item not at the folder level.



The contents of the folders can be tested using the function we saw earlier



get-mailitemcount | where {$_.Folder –like “Deleted*”}



A couple of notes on this function:



  1. Its inefficient iterating through all of the folders
  2. It doesn’t necessarily delete all of the items in one pass


The fix to this is use the get-mailitemcount function to test if we need to delete and keep calling the function until the folder is empty.  There is a way to access the folder directly that I will be testing next

Leave a Reply