-or Returning a false positive ??

This topic contains 6 replies, has 4 voices, and was last updated by Profile photo of Terry McKenna Terry McKenna 2 years, 3 months ago.

  • Author
    Posts
  • #18010
    Profile photo of Terry McKenna
    Terry McKenna
    Participant

    Hi Guys,

    Can someone tell me why I get $TRUE with this?

    $foo = @('A','B','C')
    
    if ($foo -Contains 'X') {Write-Output $foo}
    
    
    if ($foo -Contains 'X' -or 'Z') {Write-Output $foo}
    A
    B
    C
    

    Thanks

  • #18011
    Profile photo of Raymond Slieff
    Raymond Slieff
    Participant
    if (($foo -Contains 'X') -or ($foo -Contains 'Z')) {Write-Output $foo}

    Should give you what you expect.

  • #18014
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    If you read about_Operators, -or is a Logical operator used to 'to connect conditional statements into a single complex conditional.' Comparison operators such as -contains, -like, -eq ... are doing variable comparisons.

    if (($foo -Contains 'X') -or ($foo -contains 'Z')) {Write-Output $foo}
    if (($foo -Contains 'X') -and ($foo -contains 'Z')) {Write-Output $foo}

  • #18016
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    To clarify further, this expression: ($foo -Contains 'X' -or 'Z') is a compound of the following two expressions:

    [ul]
    [li]$foo -Contains 'X'[/li]
    [li]'Z'[/li]
    [/ul]

    $foo -Contains 'X' is obviously false. The expression 'Z', however, is a string, not a boolean. When strings are cast to booleans (which is what PowerShell is doing here), they're False if they are null or empty, and True if they contain any characters. As you can see if you run this:

    [bool]'Z'
    

    The second part of your original compound expression is always true.

  • #18019
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    It's interesting that Z returns true if it's casting it as boolean. Boolean is typically translated to a 0 or 1 to indicate a false or true. A bit misleading...

  • #18023
    Profile photo of Raymond Slieff
    Raymond Slieff
    Participant

    Boolean is always through of as just 0 and 1, it's more accurately Zero and Non-Zero with 0 being False, and everything else being true. Although this varies from language to language on how it gets used.

  • #18028
    Profile photo of Terry McKenna
    Terry McKenna
    Participant

    Thanks guys

You must be logged in to reply to this topic.