Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept where clause in an advanced function

Is it possible to pass a where clause to an advanced function? An example to make it more clear;

$Fruits = @(
    @{
        Name  = 'Kiwi'
        Color = 'Green'
    }
    @{
        Name  = 'Banana'
        Color = 'Yellow'
    }
)

Function Get-Stuff {
    Param (
        [scriptblock]$Filter,
        [hashtable[]]$Collection
    )

    $Collection.Where( { $Filter })
}

Get-Stuff -Filter { $_.Name -eq 'Kiwi' } -Collection $Fruits

In this case it would be great if the function can return the same as $Fruits.Where( { $_.Name -eq 'Kiwi' }).

like image 608
DarkLite1 Avatar asked Mar 20 '26 02:03

DarkLite1


1 Answers

As ansgar-wiechers stated in the above comment, you have to remove the outer scriptblock literal ({}):

$Fruits = @(
    @{
        Name  = 'Kiwi'
        Color = 'Green'
    }
    @{
        Name  = 'Banana'
        Color = 'Yellow'
    }
)

Function Get-Stuff {
    Param (
        [scriptblock]$Filter,
        [hashtable[]]$Collection
    )
    # Subexpression removed.
    $Collection.Where($Filter)
}

Get-Stuff -Filter { $_.Name -eq 'Kiwi' } -Collection $Fruits
like image 111
Moerwald Avatar answered Mar 23 '26 13:03

Moerwald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!