powershellpipelinewhere-object

Ho do I wrap Where-Object in a helper filter?


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'

Solution

  • 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.