PowerShell -contains logic question

techresearch7777777 1,981 Reputation points
2023-11-29T22:32:21.18+00:00

Hello, sorry if novice question I realize the following returns True:

"abc", "def" -contains "def"                  # Output: True

But when when adding more items why does the following return False?

"abc", "def", "ghi" -contains "abc", "def"    # Output: False

The first one seems to make sense since "def" does contain within the left side set...but the second example both "abc" & "def" looks like also exists within the left side set so I would think should return True but it doesn't?

Guess I'm missing something or not clear on this logic.

Thanks in advance.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Answer accepted by question author
  1. Rich Matheisen 48,026 Reputation points
    2023-11-30T16:49:52.7133333+00:00

    Here's another mind-bender you may run into (and it's a VERY COMMON coding error!):

    $a = 1,2,$null,4
    "There's a `$null in `$a, but `$a is an array"
    
    if ($a -eq $null){
        "`$a is `$null"
    }
    else{
        "`$a is not `$null"
    }
    "You'd expect to get either `$True or `$false for that! But . . . uh-oh!
    
    "==="   # just a separator
    "`$a isn't `$null"
    $null -eq $a
    

    To avoid this kind of conundrum, ALWAYS ALWAYS ALWAYS place the $null on the LEFT SIDE of the comparison.

    If you need help understanding why that happens, and why there's a missing $true/$false, leave a comment. :-)

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-11-30T08:49:27.5+00:00

    Hi,

    When the right-hand side operand is a collection, these operators convert the value to its string representation before comparing it to the left-hand side collection.

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.3#containment-operators

    Best Regards,

    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.