Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

Have you tried creating your own filter. (A silly) example:

filter MyFilter {
   if ( ($_ % 2) -eq 0) { Write-Host $_ }
   else { Write-Host ($_ * $_) }
}

PS> 1,2,3,4,5,6,7,8,9 | MyFilter
1
2
9
4
25
6
49
8
81

I don't know if my answer can help you but I try :)

1..10 | % {if ($_ % 2 -eq 0) {$_}} 

as you can see I use a loop and for each number between 1 and 10 I check if is even and I display it only in this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top