如何在管道内使用“if”语句

时间:2011-04-27 19:51:38

标签: powershell pipeline conditional-statements statements

我正在尝试在管道中使用if

我知道有where(别名?)过滤器,但是如果我想要在满足某个条件时激活过滤器该怎么办?

我的意思是,例如:

get-something | ? {$_.someone -eq 'somespecific'} | format-table

如何在管道内使用if来打开/关闭过滤器?可能吗?它有意义吗?

由于

已编辑以澄清

没有管道,它看起来像这样:

if($filter) {
 get-something | ? {$_.someone -eq 'somespecific'}
}
else {
 get-something
}

在ANSWER的riknik之后编辑

愚蠢的例子显示我在寻找什么。您有一个存储在变量$data上的非规范化数据表,并且您希望执行一种“向下钻取”数据过滤:

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) } |

}

例如,如果我只想按特定父级过滤:

datafilter -parent -myparent 'myparent' -data $mydata

这是一种非常优雅,高效且简单的方式来利用?。尝试使用if执行相同操作,您就会理解我的意思。

3 个答案:

答案 0 :(得分:15)

使用where-object时,条件不必严格与通过管道的对象相关。因此,考虑一下我们有时想要对奇数对象进行过滤的情况,但只有在满足其他条件的情况下:

$filter = $true
1..10 | ? { (-not $filter) -or ($_ % 2) }

$filter = $false
1..10 | ? { (-not $filter) -or ($_ % 2) }

这是你想要的吗?

答案 1 :(得分:3)

您是否尝试过创建自己的过滤器? (一个愚蠢的)例子:

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

答案 2 :(得分:2)

我不知道我的答案是否可以帮助你,但我尝试:)

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

你可以看到我使用一个循环,对于1到10之间的每个数字,我检查是否是偶数,我只在这种情况下显示它。