PowerShell -contains logic question

techresearch7777777 1,801 Reputation points

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.

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,320 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,831 Reputation points

    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"
        "`$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. Ian Xue (Shanghai Wicresoft Co., Ltd.) 34,271 Reputation points Microsoft Vendor


    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.


    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.