Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use "if" statements inside pipeline

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.

like image 413
Emiliano Poggi Avatar asked Apr 27 '11 19:04

Emiliano Poggi


2 Answers

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?

like image 83
Daniel Richnak Avatar answered Sep 19 '22 15:09

Daniel Richnak


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
like image 31
Torbjörn Bergstedt Avatar answered Sep 21 '22 15:09

Torbjörn Bergstedt