Reputation: 93
For last hours I'm trying to figure out how to pass a scriptblock to a function to be used as a filter for where object. I haven't found any documentation, I must be missing something. I saw "filter script:" and "function:script" definitions in What is the recommended coding style for PowerShell? but I have no idea how these are used and I can't find it anywhere.
function Test
{
Param(
$f,
$What
)
$x = $What | where $f
$x
}
$mywhat = @('aaa', 'b', 'abb', 'bac')
filter script:myfilter {$_ -like 'a*'}
Test -What $mywhat -xx $myfilter
Can someone please point me to the right direction?
Upvotes: 0
Views: 2979
Reputation: 54871
It's unclear what you're asking for here.
A filter is a function and not a scriptblock. where-object
takes a scriptblock as an input. If you want to specify the where condition inside a function using a parameter, you could use a scriptblock-parameter.
function Test
{
Param(
[scriptblock]$f,
$What
)
$x = $What | where $f
$x
}
$myfilter = {$_ -like 'a*'}
Test -What $mywhat -f $myfilter
#or combine them
Test -What $mywhat -f {$_ -like 'a*'}
If you simply wanted to use a filter, then this is how to do it:
filter script:myfilter { if($_ -like 'a*') { $_ }}
$mywhat | myfilter
That will be the equal to $mywhat | where {$_ -like 'a*'}
Upvotes: 2