【问题标题】:Powershell: if items in array1 contain items in array2, what am I doing wrong herePowershell:如果array1中的项目包含array2中的项目,我在这里做错了什么
【发布时间】:2017-11-11 22:03:10
【问题描述】:

我不确定我在这里做错了什么:

    $ZertoGenericAlert =  "VRA0030"
    $ZvmToVraConnection = "ZVM0002"
    $ZvmToZvmConnection = "ZVM0003", "ZVM0004"

  $thoseerrors = "ZVM0002", "VPG0006", "VPG0004" , "ZVM0003", "ZVM0004"

  if ($thoseerrors -contains $ZvmToZvmConnection) {Echo "bingo"} Else {Echo "fail"}

当我运行整段代码时,它总是“失败”

当在$zvmtozvmconnection 中找到只有一项时,它给了我“宾果游戏”

即我删除“ZVM0004”,只剩下“ZVM003”我得到“Bingo”

我还测试了-match,但也没有用

请帮忙

【问题讨论】:

标签: arrays powershell if-statement contains


【解决方案1】:

-contains 不能这样工作。它检查单个项目是否包含在数组中。 -in 同理,其他顺序($array -contains $item 或$item -in $array)。

您应该为此使用Compare-Object cmdlet:

if ((Compare-Object -ReferenceObject $thoseerrors -DifferenceObject $ZvmToZvmConnection -ExcludeDifferent -IncludeEqual)) {
    'bingo'
} else {
    'fail'
}

【讨论】:

  • 谢谢...我想他们应该修复有关 Powershell ISE 的注释和帮助,其中指出它检查数组 1 是否包含数组 2 中的至少一个项目...好吧..叹息...谢谢你
  • @A.Zia 很有趣,你在哪里看到的?
  • @A.Zia 文字是正确的,不是你所描述的。文本说该项目必须与数组中的至少一个值完全匹配,考虑像$a = 1,2,3,3 这样的数组,在这种情况下$a -contains 3 为真,即使$a 包含3 不止一次。
  • 我明白了,所以我误解了描述
【解决方案2】:

其他方法

$resul=$ZvmToZvmConnection | where {$_ -in $thoseerrors} | select -First 1

if ($resul) 
{
    'bingo'
} 
else 
{
    'fail'
}

【讨论】:

    【解决方案3】:

    作为一个班轮:

    if($thoseerrors | ? {$ZvmToZvmConnection -contains $_}) {Echo "bingo"} Else {Echo "fail"}
    

    所有错误都在一个单独的数组中。

    # Existing errors stored in $errors
    $errors = $thoseerrors | Where {$ZvmToZvmConnection -contains $_}
    
    # Check if the $errors array contains elements
    if($errors){Echo "bingo"} Else {Echo "fail"}
    

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2016-03-03
      • 2013-06-28
      • 2023-01-19
      相关资源
      最近更新 更多