views:

27

answers:

0

I'm retrieving the UnReadItemCount from several Outlook folders in a PowerShell WPK application. I create an Outlook.Application object, get the Session, and do a tour of the Folders, saving the Folder objects of interest in PowerShell variables. Then I retrieve the UnReadItemCounts from the saved Folder objects and display them in the WPK window. This works perfectly once. When I later query the same UnReadItemCounts in the saved Folders, they never change, even when there are new unread items in the folders.

I'm assuming this is because PowerShell is saving a static, unlinked copy of the MAPIFolder object, rather than a reference to the live folder. Working on that theory, I'm going to walk back up the chain to see how far I have to go to get live objects. I'm fairly new to PowerShell, and I'm not aware of any explicit way to reference an existing object rather than copy it (as in ByRef vs. ByVal in VBscript). Can anyone confirm that behavior of PowerShell? Or, alternatively, find a bug in my code, or a workaround that refreshes the folder properties? Here's the code snippet:

$topfolder = "My Top Mailbox Folder" # YMMV -- I have several top Outlook folders
$foldernames = "Inbox","Drafts"
$folders = $null,$null
$oapp = New-Object -ComObject Outlook.Application
$ons = $oapp.Session
$ons.Logon()
foreach ($ofldr1 in $ons.Folders) {
    if ($ofldr1.Name -eq $topfolder) {
        for ($i = 0; $i -lt $foldernames.count; $i++) {
            foreach ($ofldr2 in $ofldr1.Folders) {
                if ($ofldr2.Name -eq $foldernames[$i]) { $folders[$i] = $ofldr2 }
            }
        }
    }
}

The above is executed once, getting the folder objects in $folders corresponding to the names in $foldernames. Then I later reference $folders[0].UnReadItemCount, for example, to get the number of unread emails in the Inbox. As I said, this works once, but then never changes. I know the loop can be optimized, and made to look more PowerShell-ish. Any other advice will be much appreciated.

As an additional note, this code is executed inside a WPK window On_Loaded event, in case that makes any difference. I tried to add the WPK tag, but I'm a few points shy of the required reputation. If you have 1500 rep, please add that tag.