-1

I have this code:

$resultset = $stuff | Where-Object { $_.Prop1.SubProp7 -eq 'SearchString' }

Very similar code is repeated quite a few times. (in a Pester test).

How can I wrap that code in a simple filter helper?

filter Where-Subprop7($SearchString) {
  <#??#> | Where-Object { $_.Prop1.SubProp7 <#??#> -eq $SearchString } | ...???
}

$resultset = $stuff | Where-Subprop7 'SearchString'
Martin Ba
  • 37,187
  • 33
  • 183
  • 337

2 Answers2

0

You can write a small function to generate the filter block:

function New-WhereSubprop7Filter {
    param($SearchString)

    return {
        $_.Prop7.SubProp7 -eq $SearchString
    }.GetNewClosure()
}

Then use like:

$resultset = $stuff |Where-Object (New-WhereSubprop7Filter 'SearchString')

The call to GetNewClosure will create a closure over the $SearchString variable, making the scriptblock "remember" the 'SearchString' value passed when invoking New-WhereSubprop7Filter.

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

It would indeed appear to be as straightforward as:

filter _WhereMyKey($key) {
  $_ | Where-Object { $_.Prop1.SubProp7 -eq $key }
}

This code works fine for me in my Pester expression:

$($stuff | _whereMyKey 'X-123').User | Should -Match 'Joe'
$($stuff | _whereMyKey 'Y-123').User | Should -Match 'Jane'

I did not use the naming Where- because it is a reserved verb.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337