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.
When using where-object, the condition doesn't have to strictly be related to the objects that are passing through the pipeline. So consider a case where sometimes we wanted to filter for odd objects, but only if some other condition was met:
$filter = $true
1..10 | ? { (-not $filter) -or ($_ % 2) }
$filter = $false
1..10 | ? { (-not $filter) -or ($_ % 2) }
Is this kind of what you are looking for?