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'
CodePudding user response:
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
.
CodePudding user response:
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.