更新时间:2023-11-04 11:02:40
抱歉,我不是有意放弃这个问题的.发布的答案不是我想要的,但我在发布后不久就想出了一种方法,并且很长时间没有回到该网站.由于尚未发布解决方案,这就是我想出的.当我问这个问题时,这并不是我的想法,也不是太漂亮,但显然这是唯一的方法:
Sorry, I didn't mean to abandon this question. The answers that were posted weren't what I was driving at, but I figured out a way to do it shortly after posting, and didn't come back to the site for a long time. Since a solution hasn't been posted, here's what I came up with. It's not quite what I had in mind when I asked the question and it isn't too pretty, but apparently it's the only way to do it:
<statement> | <filter1> | foreach {if (<condition>) {$_ | <filter2>} else {$_} | <filter3> | <filter4> | <filter5>
因此,在示例中,该行
|where {$_.psiscontainer} `
将改为
|foreach {if (-not $files) {$_ | where {$_.psiscontainer}} else {$_}} `
和
|where {$_.isinherited -eq 'False'} `
将改为
|foreach {if (-not $inherited) {$_ | where {$_.isinherited -eq 'False'}} else {$_}} `
(是的,通常我会把它写成 |foreach {if ($files) {$_} else {$_ | where {$_.psiscontainer}}}
和 |foreach {if ($inherited) {$_} else {$_ | where {$_.isinherited -eq 'False'}}}
但为了清楚起见,我是这样做的.)
(Yes, normally I'd write that as |foreach {if ($files) {$_} else {$_ | where {$_.psiscontainer}}}
, and |foreach {if ($inherited) {$_} else {$_ | where {$_.isinherited -eq 'False'}}}
but I did it this way for clarity.)
我希望可能有更优雅的东西,它会评估过滤器前面的条件一次,以确定是执行还是跳过管道的一个阶段.像这样:
I was hoping there might be something more elegant, that would evaluate a condition in front of the filter once to determine whether to execute or skip a stage of the pipeline. Something like this:
<statement> | <filter1> | if (<condition>) {<filter2>} | <filter3>
(if
的特例,不是通常的意思;可以使用不同的关键字),或者
(a special case of if
, not the usual meaning; a different keyword could be used), or maybe
<statement> | <filter1> | (<condition>) ? <filter2> | <filter3>
$_
在条件中无效,除非它是在当前管道之外定义的,例如如果管道包含在 switch
语句中,$
将引用
中的 _switch
语句的 $_
.
$_
would be invalid in the condition, unless it's defined outside the current pipeline, for example if the pipeline is contained within a switch
statement, $_
in the <condition>
would refer the switch
statement's $_
.
我想我会向 Microsoft 提出功能建议.这不仅会使代码更优雅,而且效率也会更高,因为如果它是一个内置特性,
可以被评估一次整个管道,而不是在每次迭代中测试相同的独立条件.
I think I'll make a feature suggestion to Microsoft. This would not only make the code more elegant, it would be more efficient as well, because if it's a built-in feature, <condition>
could be evaluated once for the entire pipeline, rather then testing the same independent condition in each iteration.