2

I'm running the following PowerShell code to retrieve matches in my inbox and wondering why my filter isn't working for instances where there's only a single match. Here's the code to find and filter the matches;

 Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null 
 $olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]  
 $outlook = new-object -comobject outlook.application 
 $namespace = $outlook.GetNameSpace("MAPI") 
 $inbox = $namespace.getDefaultFolder($olFolders::olFolderInBox) 
 $filter = (%{$inbox.items | Where {$_.SenderName -match ‘JoeUser’ -and
 $_.UnRead -eq $true}})

...and when I ask for a count of matches by running $filter.count, I get the correct answer AS LONG AS there is more than one match. So, for scenarios where there is only a single, matching message in my inbox, the $filter.count doesn't return anything and teh subsequent code fails to process on the message- and I know that the match picked up the matching message because I can view it from $filter

Can anyone figure out why this count doesn't work on a single match from $filter?

mandg
  • 87
  • 1
  • 4

2 Answers2

6

A variable doesn't get cast as an array when only one value is returned by the right hand side of the assignment.

There are a bunch of previous questions dealing with this:

Can be fixed by adding '@' as follows:

$filter = @(%{$inbox.items | Where {$_.SenderName -match ‘JoeUser’ -and $_.UnRead -eq $true}})

Apparently, this behavior changes in PowerShell v3: http://arstechnica.com/civis/viewtopic.php?t=1235149

Community
  • 1
  • 1
pabrams
  • 1,157
  • 10
  • 34
  • Thanks! That little ampersand worked as you stated! Evidently that changed my $filter from a string to an array and now my $filter.count correctly shows a value of 1. Apologies for the redundant question. – mandg Jul 09 '16 at 04:21
5

Beside what others suggest you can always get correct answer with $filter | measure | % count

majkinetor
  • 8,730
  • 9
  • 54
  • 72