I have been using PS for about 8-9 years. I want to use a SQL table to store a list of values to use in an exclusion WHERE Object clause. The source data is NOT in SQL. It is coming from a data set coming from an Outlook COM object. Basically I want to filter out emails that have certain keywords in the subject. It already has a static list that works just fine, but I would like to give the users the ability to modify this list without updating the code. Here is what I have. It looks like it 'Should' work. In fact, if I render the filter and past it into the WHERE Object, it does work. Just not with the string variable.
$dsExclude = Select-SQL "SELECT Keyword = LTRIM(RTRIM(Keyword)) FROM Email_Mining_Keywords WHERE Action='Exclude' AND WordLocation='Subject'" -ConnectionStringOrSetting $DestConnectionString
$filter = ($dsExclude | select -ExpandProperty KeyWord | % { "`$_.Subject -NOTlike '*$_*'" }) -join ' -and '
$dsResults | ?{$filter} | Out-GridView
It took me awhile to figure out that I needed to escape the pipe character from the source dataset while parsing the pipe character from the exclusion dataset. When rendering the filter variable, it looks great & works when manually pasting the filter.
$filter = [scriptblock]::Create($filter)
then? $filter
(no{..}
). However what you're trying to do is terribly inefficient. You could just build a single regex OR pattern and do? { $_.Subject -notmatch $bigOrRegexPattern }
$filter
is a non-empty[string]
, not an executable expression, so yourwhere-object
(the? { ... }
) is equivalent towhere-object { $true }
.