Flexible Filtering

When writing a “get-” function in PowerShell, you often run into the issue of filtering your data.  Do you want to include any filtering parameters?  Do you want to allow lists of values?  Do you want to provide “include” or “exclude” parameters?  What about wildcards?  I got tired of writing the same kind of code over, so I wrote a fairly general-purpose filter-list function.

Here it is (example usages follow):

function filter-list($list, $filterString,$propertyName,[switch]$help ){
 if ($help)
 $msg = @"
Filter a list using a filterstring and a property name. Wildcards are allowed, as well as
a prefix of Not:, which means to include values that don't match the pattern.
If filterString is an array, it lists property values that will remain in the list.

Usage: filter-list list filterString propertyname [-help]
 Write-Host $msg
 if (!$list) {return}
 if ($filterString -is [Array]){
 $list = @($list | ?{ $filterString -icontains $_.$propertyName})
 } else
 if (($filterString) -and ($filterString -ne '')){
 if ($filterString -ilike 'Not:*'){
 $list = @($list | ? {$_.$propertyName -inotlike $filterString.Replace('Not:','')})
 } else {
 $list = @($list | ? {$_.$propertyName -ilike $filterString})
 return $list

Here’s a simple function (not really useful) that uses this:

function new-dir{
 Param($path, $extension)
 $list=dir $path
 $list=filter-list $list $extension Extension

 return $list

new-dir -path c:temp -ext '.LOG','.TXT'
new-dir -path c:temp -ext 'Not:.LOG'
new-dir -path c:temp -ext 'Not:.c*'

Now, without really writing any new code, we have a parameter that can take simple values, lists of values, wildcards, and include/exclude logic.

Let me know what you think of this.