PowerShell 计数不适用于单个匹配项 [英] PowerShell count not working for single matches

查看:55
本文介绍了PowerShell 计数不适用于单个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下 PowerShell 代码来检索收件箱中的匹配项,但想知道为什么我的过滤器对只有一个匹配项的实例不起作用.这是查找和过滤匹配项的代码;

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}})

...并且当我通过运行 $filter.count 要求匹配的计数时,只要有多个匹配,我就会得到正确的答案.因此,对于我的收件箱中只有一条匹配消息的情况,$filter.count 不返回任何内容,并且后续代码无法处理消息 - 我知道match 选择了匹配的消息,因为我可以从 $filter

...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

谁能弄清楚为什么这个计数对 $filter 的单个匹配不起作用?

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

推荐答案

当赋值的右侧只返回一个值时,变量不会被强制转换为数组.

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}})

显然,此行为在 PowerShell v3 中发生了变化:http://arstechnica.com/civis/viewtopic.php?t=1235149

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

这篇关于PowerShell 计数不适用于单个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆