13

在 PowerShell v2 中,我尝试仅向数组添加唯一值。我试过使用一个 if 语句,粗略地说,如果(-not $Array -contains 'SomeValue'),然后添加值,但这只会在第一次工作。我放了一个简单的代码片段,显示了我在做什么但不起作用,以及我做了什么作为一种有效的解决方法。有人可以让我知道我的问题在哪里吗?

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”。任何帮助是极大的赞赏。

4

2 回答 2

15

要修复您的代码,请尝试-notcontains或至少将您的 contains-test 包装在括号中。自动取款机。您的测试内容如下:

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

这是没有意义的。你想要的是:

如果数组不包含单词..

是这样写的:

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

-notcontains正如@dugas 建议的那样,甚至更好。

于 2013-04-22T18:22:42.287 回答
7

The first time around, you evaluate -not against an empty array, which returns true, which evaluates to: ($true -contains 'AnyNonEmptyString') which is true, so it adds to the array. The second time around, you evaluate -not against a non-empty array, which returns false, which evaluates to: ($false -contains 'AnyNonEmptyString') which is false, so it doesn't add to the array.

Try breaking your conditions down to see the problem:

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

then add an element to the array:

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

See the problem? Your current syntax does not express the logic you desire.

You can use the notcontains operator:

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

# This will work
$IncorrectArray = @()
ForEach ($Word in $Words)
{
  If ($IncorrectArray -notcontains $Word)
  {
    $IncorrectArray += $Word
  }
}
于 2013-04-22T18:07:46.310 回答