简体   繁体   English

PowerShell Where-Object-如何对条件进行分组

[英]PowerShell Where-Object - How to group conditions

I have a PowerShell script with a variable that is piped into "where-object". 我有一个带有变量的PowerShell脚本,该变量通过管道传递到“ where-object”。 This where clause contains multiple statements that have to be true (-AND) and two statements, where at least one has to be true (-XOR). 该where子句包含多个必须为true的语句(-AND)和两个语句,其中至少一个必须为true的语句(-XOR)。 How do I group them? 如何将它们分组? Nothing I've tried worked so far: 到目前为止,我没有尝试过的工作:

$var | Where-Object { condition1 -AND condition2 -AND condition3 -XOR condition4 }
$var | Where-Object { condition1 -AND condition2 -AND (condition3 -XOR  condition4) }    
$var | Where-Object { (condition1 -AND condition2) -AND condition3 -XOR  condition4 }
$var | Where-Object { (condition1 -AND condition2) -AND (condition3 -XOR condition4) }

Can you help me? 你能帮助我吗?

Thanks in advance! 提前致谢!

Did you tried this one : 您是否尝试过这个:

$var | Where-Object { condition1 -AND condition2 -AND (condition3 -OR  condition4) } 

As a side reminder, here's the Microsoft official man page that can interest you : 提醒一下,这是您可能感兴趣的Microsoft官方手册页

    -or       Logical or. TRUE when either     (1 -eq 1) -or (1 -eq 2) 
              or both statements are TRUE.     True


    -xor      Logical exclusive or. TRUE       (1 -eq 1) -xor (2 -eq 2)
              only when one of the statements  False 
              is TRUE and the other is FALSE.

And since I'm here, another tought : Depending on the size and structure of your $var object, checking ALL conditions on ALL Objects can take some time, you should filter it : 而且由于我在这里,所以另一个难点是:根据$ var对象的大小和结构,检查所有对象上的所有条件可能需要一些时间,您应该对其进行过滤:

Reminder : ? 提醒: is a natural alias to Where-Object : Where-Object的自然别名:

$var | ? { condition1 } |? { condition2 } |? { condition3 -OR  condition4 } 

This might help your script to go faster ... 这可能有助于您的脚本执行得更快...

Thank you for all the suggestions and possibilities to check the outcome of the conditions. 感谢您提供所有建议和检查条件结果的可能性。 In the end I've used a slightly different solution: 最后,我使用了稍微不同的解决方案:

if ( $var | Where-Object { condition1 -AND condition2 -AND condition3 } ) {
    Write-Host "Do some stuff"
    }
else {
    if ( $var | Where-Object { condition1 -AND condition2 -AND condition4 } ) {
        Write-Host "Do other stuff"
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM