header image

Clearing junk mail

Posted by: | August 2, 2011 | 4 Comments |

Getting back to looking at working with Outlook we can adapt the function used to deleted the contents of the Deleted Items folder to work with the Junk mail folders

function clear-junkmail {            
$outlook = New-Object -ComObject Outlook.Application            
get-mailitemcount -junk            
$folders | where {$_.Path -like "*junk*"} |            
foreach {             
  $mailfolder = $outlook.Session.GetFolderFromID($_.EntryID, $_.StoreID)            
  if ($mailfolder.Items.Count -gt 0){            
    do {            
      foreach ($item in $mailfolder.Items){$item.Delete()}            
    } while ($mailfolder.Items.Count -gt 0)            
get-mailitemcount -junk            

Very much the same as before but we are looking for folders that contain the work “junk”

It would be possible to combine this function and the clear-deletedmail function but I decided to keep them separate for simplicity

under: Office 2010, Outlook, PowerShellV2, Windows 7


  1. By: Robert on August 2, 2011 at 3:01 pm      

    You should really check out the GetDefaultFolder method so you don’t have to loop through all the folders.

  2. By: RichardSiddaway on August 3, 2011 at 3:20 am      

    The GetDefaultFolder method only returns the folders for the mailbox that is designated as the primary – usually the first one you connect to.

    The whole point of these posts is dealing with multiple mailboxes which means you have to take a slightly different approach as I pointed out in an earlier post

  3. By: jcwfbi on August 3, 2011 at 9:01 am      

    What about if you created a custom folder, like for a certain person, and you wanted to do the same with that? How would that work? Also what about a pst backup?

  4. By: RichardSiddaway on August 4, 2011 at 11:18 am      

    This post http://msmvps.com/blogs/richardsiddaway/archive/2011/08/04/outlook-deleting-mail-items.aspx

    shows how to delete the mail items in a particular folder