如何使用"if"管道中的语句 [英] how to use "if" statements inside pipeline
问题描述
我正在尝试在管道内使用if
.
I'm trying to use if
inside a pipeline.
我知道有where
(别名为?
)过滤器,但是如果我想仅在满足特定条件的情况下才激活过滤器,该怎么办?
I know that there is where
(alias ?
) filter, but what if I want activate a filter only if a certain condition is satisfied?
我的意思是,例如:
get-something | ? {$_.someone -eq 'somespecific'} | format-table
如何在管道内使用if
来打开/关闭过滤器?是否有可能?有道理吗?
How to use if
inside the pipeline to switch the filter on/off? Is it possible? Does it make sense?
谢谢
已编辑以澄清
没有管道,它看起来像这样:
Without pipeline it would look like this:
if($filter) {
get-something | ? {$_.someone -eq 'somespecific'}
}
else {
get-something
}
在ANSWER的riknik之后进行编辑
显示我正在寻找的傻事示例.您有一个存储在变量$data
上的非规范化数据表,并且想要执行一种向下钻取"数据过滤:
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
这是利用?
的非常优雅,高效且简单的方法.尝试使用if
做同样的事情,您会明白我的意思.
That's very elegant, performant and simple way to exploit ?
. Try to do the same using if
and you will understand what I mean.
推荐答案
使用where-object时,条件不必严格与通过管道的对象相关.因此,考虑一种情况,有时我们想过滤奇数个对象,但前提是要满足其他一些条件:
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?
这篇关于如何使用"if"管道中的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!