DarkLite1
DarkLite1

Reputation: 14705

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' }).

Upvotes: 3

Views: 53

Answers (1)

Moerwald
Moerwald

Reputation: 11264

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

Upvotes: 3

Related Questions