header image

Outlook Connector & mail folder item count

Posted by: | July 30, 2011 | No Comment |

On my home laptop I use Live Mail to aggregate my hotmail accounts. On my travelling netbook I decided to try the Outlook Connector


This add in enables you to access hotmail accounts from Outlook & because I’m using Outlook 2010 I can have multiple mailboxes open at once.

This leads to some interesting PowerShell opportunities as having multiple mailboxes open means that some of the standard approaches won’t work – most scripts you see assume that you are connecting to an Exchange mailbox and that there is only one of them.

As an example consider getting a list of all of the mail folders and the number of items in each

function get-mailitemcount {            
Add-Type -Assembly Microsoft.Office.Interop.Outlook            
$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]            
$outlook = New-Object -ComObject Outlook.Application            
foreach ($folder in $outlook.Session.Folders){            
  foreach($mailfolder in $folder.Folders ) {            
    New-Object -TypeName PSObject -Property @{            
      Mailbox = $($folder.Name)            
      Folder = $($mailfolder.Name)            
      ItemCount = $($mailfolder.Items.Count)            
    } | select Mailbox, Folder, ItemCount            

The first two lines add the interop assembly and create an object representing the default folders. If these are used directly all we get is the folders for the default (first) mailbox.

Create an object for the outlook application and iterate through the folders in the session – these are the individual mailboxes.

For each of those create an object and set the properties. The select ensures the object properties display in the order we need.

I used foreach instead of foreach-object so that I could use a variable rather than $_ as it would have confusing with nested foreachs

There is quite a bit to play with here and some very interesting PowerShell issues.

under: COM, Office 2010, PowerShellV2, Windows 7