I'm trying to use if
inside a pipeline.
I know that there is where
(alias ?
) filter, but what if I want activate a filter only if a certain condition is satisfied?
I mean, for example:
get-something | ? {$_.someone -eq 'somespecific'} | format-table
How to use if
inside the pipeline to switch the filter on/off? Is it possible? Does it make sense?
Thanks
EDITED to clarify
Without pipeline it would look like this:
if($filter) { get-something | ? {$_.someone -eq 'somespecific'} } else { get-something }
EDIT after ANSWER's riknik
Silly example showing what I was looking for. You have a denormalized table of data stored on a variable $data
and you want to perform a kind of "drill-down" data filtering:
function datafilter { param([switch]$ancestor, [switch]$parent, [switch]$child, [string]$myancestor, [string]$myparent, [string]$mychild, [array]$data=[]) $data | ? { (!$ancestor) -or ($_.ancestor -match $myancestor) } | ? { (!$parent) -or ($_.parent -match $myparent) } | ? { (!$child) -or ($_.child -match $mychild) } | }
For example, if I want to filter by a specific parent only:
datafilter -parent -myparent 'myparent' -data $mydata
That's very elegant, performant and simple way to exploit ?
. Try to do the same using if
and you will understand what I mean.