0

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?

1 Answer 1

2

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*'}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Graimer! That's what I was looking for and I believe I have tried this in the very beginning - had to still have something wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.