仅在数组不存在时添加到数组中

问题描述 投票:0回答:2

在 PowerShell v2 中,我尝试仅向数组添加唯一值。我尝试过使用 if 语句,粗略地说,If (-not $Array -contains 'SomeValue'), then add the value,但这仅在第一次有效。我放置了一个简单的代码片段,显示了我正在做的不起作用的事情以及我所做的作为可行的解决方法的事情。有人可以告诉我我的问题出在哪里吗?

Clear-Host
$Words = @('Hello', 'World', 'Hello')

# This will not work
$IncorrectArray = @()
ForEach ($Word in $Words)
{
    If (-not $IncorrectArray -contains $Word)
    {
        $IncorrectArray += $Word
    }
}

Write-Host ('IncorrectArray Count: ' + $IncorrectArray.Length)

# This works as expected
$CorrectArray = @()
ForEach ($Word in $Words)
{
    If ($CorrectArray -contains $Word)
    {
    }
    Else
    {
        $CorrectArray += $Word
    }
}

Write-Host ('CorrectArray Count: ' + $CorrectArray.Length)

第一个方法的结果是一个仅包含一个值的数组:“Hello”。第二个方法包含两个值:“Hello”和“World”。非常感谢任何帮助。

arrays powershell foreach contains
2个回答
17
投票

要修复您的代码,请尝试

-notcontains
或至少将您的 contains-test 包裹在括号中。自动取款机。你的测试内容是:

如果“NOT array”(如果数组不存在)包含单词。

这毫无意义。你想要的是:

如果数组不包含单词..

是这样写的:

If (-not ($IncorrectArray -contains $Word))

-notcontains
更好,正如@dugas 所建议的。


9
投票

第一次,您对空数组进行评估 -not ,它返回 true,其评估结果为: ($true -contains 'AnyNonEmptyString') 这是 true,因此它添加到数组中。第二次,您针对非空数组评估 -not ,它返回 false,其计算结果为: ($false -contains 'AnyNonEmptyString') 这是 false,因此它不会添加到数组中。

尝试分解你的条件来查看问题:

$IncorrectArray = @()
$x = (-not $IncorrectArray) # Returns true
Write-Host "X is $x"
$x -contains 'hello' # Returns true

然后向数组添加一个元素:

$IncorrectArray += 'hello'
$x = (-not $IncorrectArray) # Returns false
    Write-Host "X is $x"
$x -contains 'hello' # Returns false

看到问题了吗?您当前的语法无法表达您想要的逻辑。

您可以使用 notcontains 运算符:

Clear-Host
$Words = @('Hello', 'World', 'Hello')

# This will work
$IncorrectArray = @()
ForEach ($Word in $Words)
{
  If ($IncorrectArray -notcontains $Word)
  {
    $IncorrectArray += $Word
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.