Powershell Only Add to Array if it doesn't exist

后端 未结 2 1461
别那么骄傲
别那么骄傲 2021-01-17 11:49

In PowerShell v2, I\'m trying to add only unique values to an array. I\'ve tried using an if statement that says, roughly, If (-not $Array -contains \'SomeValue\'), then ad

相关标签:
2条回答
  • 2021-01-17 12:20

    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
      }
    }
    
    0 讨论(0)
  • 2021-01-17 12:24

    To fix your code, try -notcontains or at least WRAP your contains-test in parantheses. Atm. your test reads:

    If "NOT array"(if array doens't exist) contains word.

    This makes no sense. What you want is:

    If array does not contain word..

    That's written like this:

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

    -notcontains is even better, as @dugas suggested.

    0 讨论(0)
提交回复
热议问题