我使用PS大约有10年了。今天,我一直在寻找一个问题的解决方案,我希望在从 SQL 表加载的 WHERE 对象中使用项目。根据我所读到的内容,我需要构建一个过滤器对象来构建 WHERE... -and 子句,我已正确渲染该对象,但是当我尝试将该过滤器应用于该对象时,它绝对不会进行过滤,或者它奇怪地为数据集中的每条记录返回 WHERE 子句。但是当我粘贴渲染的 $filter 文本时,它确实有效,过滤掉了所有记录。
数据集由 OUTLOOK com 对象填充,它基本上是我要过滤的电子邮件列表。当我使用过滤器变量运行脚本时,它不会过滤任何内容,但是当我手动传递渲染的过滤器文本时,它似乎可以工作: 结果 :
$dsResults = Get-OutlookInBox -cutoff $cutoff | select Subject, ReceivedTime, Importance, SenderName, body
#The below is how I am loading the exclusion list from SQL and building the $filter
$dsExclude = Select-SQL "SELECT Keyword = LTRIM(RTRIM(Keyword)) FROM Email_Mining_Keywords WHERE Action='Exclude' AND WordLocation='Subject'" -ConnectionStringOrSetting $DestConnectionString
#The below filter does render correctly
$filter = ($dsExclude | select -ExpandProperty KeyWord | % { "Subject -notlike '*$_*'" }) -join ' -and '
$dsResults | select -ExpandProperty subject | ?{$filter} | Out-GridView `
#The results do not appear to filter anything (see image attachement)
[Results after filtering][1]
But it works when I past the rendered $filter:
$dsResults | ?{$_.Subject -notlike '*ENROLLMENT PACKAGE*' -and $_.Subject -notlike '*ENRPKG*' -and $_.Subject -notlike '*FW:*' -and $_.Subject -notlike '*FWD:*' -and $_.Subject -notlike '*RE:*' -and $_.Subject -notlike '*REPRINT*' -and $_.Subject -notlike '*RETURN*' -and $_.Subject -notlike '*UPDATED*'} | Out-GridView
我花了一点时间才明白我需要转义 $filter 中主题前面的管道对象。
$filter
包含一段合成的源代码作为字符串。
因此,将
{$filter}
与 Where-Object
(?
) 一起使用始终为 $true,因为任何非空字符串在布尔上下文中都会被强制为 $true
。
要获得所需的行为,您必须从源代码字符串构造一个脚本块:
$filter =
[scriptblock]::Create(
($dsExclude | select -ExpandProperty KeyWord | % { "Subject -notlike '*$_*'" }) -join ' -and '
)