Powershell Only Add to array if it does not exist

In PowerShell v2, I try to add only unique values ​​to the array. I tried using the if statement, roughly speaking, If (-not $ Array -contains 'SomeValue'), then add a value, but this only ever works the first time. I put in a simple code snippet that shows what I am doing, what is not working and what I have done as a workaround that works. Can someone please let me know where my problem is?

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)

The result of the first method is an array containing only one value: "Hello". The second method contains two values: "Hello" and "World". Any help is appreciated.

+5
source share
2 answers

, -notcontains WRAP your contains-test . . :

"NOT array" ( ) .

. :

..

:

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

-notcontains , @dugas.

+5

- , true, : ($ true -contains "AnyNonEmptyString" ), , . - , false, : ($ false -contains "AnyNonEmptyString" ), , .

, :

$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
  }
}
+3

All Articles