Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Why does truth contain lies?

Tags:

powershell

PS C:\> $true -contains "Lies"
True

...?

help about_operators says

comparison operators include the containment operators (in, -notin, -contains, -notcontains), which determine whether a test value appears in a reference set.

$true is not a collection, how can it be a "reference set" and contain ... anything at all? It doesn't contain falsey things.


Similarly $null -in $null is True

like image 946
TessellatingHeckler Avatar asked Jun 23 '16 21:06

TessellatingHeckler


People also ask

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.

Is PowerShell equal?

The equality operators are equal (-eq), not equal (-ne), greater than (-gt), greater than or equal (-ge), less than (-lt), and less than or equal (-le). PowerShell doesn't use an equals sign (=) to test equality because it's used for the assignment operator.

Why pipeline is used in PowerShell?

A pipeline is a series of commands connected by pipeline operators ( | ) (ASCII 124). Each pipeline operator sends the results of the preceding command to the next command. The output of the first command can be sent for processing as input to the second command. And that output can be sent to yet another command.

How do I throw an exception in PowerShell?

To create our own exception event, we throw an exception with the throw keyword. This creates a runtime exception that is a terminating error. It's handled by a catch in a calling function or exits the script with a message like this.


1 Answers

$true get converted to a collection of 1 element, so it's equivalent to:

# ~> @($true) -contains "Lies"
True

So each element in the collection gets compared to "Lies" :

# ~> $true -eq "Lies"
True

So the real question is, why does the above expression evaluate to true. What's happening is that it is converting the right hand side of the oepration to match the type of the left hand side:

# ~> $true -eq [Bool]"Lies"
True

because:

# ~> [Bool]"Lies"
True

so if you swap the operation:

# ~> "Lies" -eq $true
False

because:

# ~> [String]$true
True

Similarly, $null -in $null is the same as $null -in @($null) and $null -eq $null is true.

like image 55
zdan Avatar answered Oct 31 '22 08:10

zdan