【问题标题】:Adding multiple -and and -or statements in WHERE clause in Powershell在 Powershell 的 WHERE 子句中添加多个 -and 和 -or 语句
【发布时间】:2019-06-14 21:04:06
【问题描述】:

我目前正在使用 Powershell,我正在尝试对我从另一个系统中提取的变量中的数据进行排序。目前我正在尝试在 -eq 符号之后使用一个 -and 语句和 -or 语句。所以我想知道在 where 语句中创建语法的正确方法是什么。

$DLPList | Select Node.NodeName, Properties.OSType, PropsView.version, Node.NodeTextPath2 | where PropsView.version -ne '1.4.706.172' -and (Properties.OSType -eq $win7 -or $win8 -or $win81 -or $win10)

我知道这方面还有很多其他的东西,但是到目前为止我尝试过的所有方法都不起作用。感谢您的帮助。

【问题讨论】:

  • 您的Select-Object 部分有效吗?我以前从未见过Property.SubProp 使用过。对于-or 的东西......你不能像那样组合它们。你可能会使用$Thing -in @($OneThing, $TwoThing, $ThreeThing)。
  • FWIW,似乎@trevor-lines 在这里回答了他的问题:stackoverflow.com/a/56634283/182742

标签: powershell


【解决方案1】:

是的,您必须使用 where-object 的脚本块版本。另请注意 -and 和 -or 在 powershell 中具有 EQUAL PRECEDENCE ,这在语言中是非常不寻常的。

【讨论】:

    【解决方案2】:

    好吧,我发现你不能只添加 use -or。相反,您必须为每一个执行 Properties.ostype。这是我想出的让它工作的代码。还有一个小技巧是在 Select-Object 之前做 Where-Object 以节省计算能力。

    $DLPList = $list1 | Where-Object{ $_.'UDLP.prodversion' -lt '9.5.704.112' -and ($_.'Properties.OSType' -ne 'Windows XP') -and ($_.'EPOComputerProperties.OSType' -ne 'Windows Vista') -and ($_.'EPOComputerProperties.OSType' -ne 'Windows 2003') -and ($_.'Properties.OSType' -ne 'Windows 2003 R2') -and ($_.'EPOComputerProperties.OSType' -ne 'Windows 2008') -and ($_.'Properties.OSType' -ne 'Windows 2008 R2') -and ($_.'Properties.OSType' -ne 'Windows Server 2012' -and ($_.'Properties.OSType' -ne 'Windows Server 2012 R2') -and ($_.'Properties.OSType' -ne 'Windows Server 2016')) } | Select-Object Node.NodeName, Properties.OSType, UDLP.productversion, Node.NodeText | Sort-Object -Property Node.NodeText -Descending
    

    【讨论】:

      【解决方案3】:

      尝试添加括号并将链式布尔运算符替换为正则表达式“-match”运算符条件:

      $DLPList | Select Node.NodeName, Properties.OSType, PropsView.version, Node.NodeTextPath2 | where { $_.'PropsView.version' -ne '1.4.706.172' -and ($_.'Properties.OSType' -match "($win7|$win8|$win81|$win10)") }
      

      以下是适用于我的示例代码:

      $DLPList = @(2, 4, 6, 7)
      $DLPList | where { ($_ -ne 7) -and ($_ -lt 10) -and ($_ -gt 0) }
      2
      4
      6
      
      $DLPList | where { ($_ -ne 7) -and ($_ -match "(4|5|11)" -and ($_ -gt 0)) }
      4
      

      【讨论】:

      • 第二行是错误。 [sigh ...] 它会给你2,4,6 ... 和2 和6 都不是正确的结果。原因是第二部分执行$_ -eq 4,然后将 boolean 与-or 5 进行比较。 ///// 你没有做你认为你正在做的事情。 [咧嘴]
      • @Lee_Dailey 当然,你是对的;谢谢你。我已更新答案以使用正则表达式“-match”运算符。
      • 酷!很高兴看到它已修复并正常工作... [grin] 这是链接逻辑运算符的经典错误 - 我已经不止一次这样做了!
      • 那不是 $_.PropsView.version 和 $_.Properties.OSType 吗?
      猜你喜欢
      • 2014-09-01
      • 2017-05-02
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      相关资源
      最近更新 更多