how to use “if” statements inside pipeline

2020-05-23 11:15发布

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.

3条回答
祖国的老花朵
2楼-- · 2020-05-23 12:10

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.

查看更多
再贱就再见
3楼-- · 2020-05-23 12:16

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?

查看更多
家丑人穷心不美
4楼-- · 2020-05-23 12:20

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
查看更多
登录 后发表回答