Question:
Looking that the help section about_Comparison_Operators of PowerShell I understand this:
1 2 3 |
PS C:\> $false,$false -eq $true PS C:\> |
Nothing from the left matches the right so nothing is returned not even a $null
.
I don’t understand this:
1 2 3 4 |
PS C:\> $true -eq $false,$false True PS C:\> |
Is it because it’s first doing $true -eq $false
which returns False, and then taking that False and doing $false -eq $false
which returns True?
More Info
The reason the below returns false is because it’s comparing a string to an array, correct? A string is not equal to an array.
1 2 3 |
PS C:\> "abc" -eq "abc","def" False |
Answer?
More digging shows that $true
is equal to an object.
1 2 3 4 5 6 7 8 9 |
PS C:\> $true -eq [array] True PS C:\> $true -eq [string] True PS C:\> $true -eq [int] True PS C:\> $true -eq [bool] True |
It’s the values of those object that matter.
1 2 3 |
PS C:\> $true -eq [int]0 False |
Answer:
I like fundamental questions about the behavior and features of the language like this… Give’s me an excuse to read the PowerShell language specification.
You can download said specification: 2.0 and 3.0. See section 7.8.1 – Equality and relational operators.
For the first part of the question, something actually is returned – an empty array, which is illustrated by: ($false,$false -eq $true).psbase
1 2 3 4 5 6 7 8 9 |
Length : 0 LongLength : 0 Rank : 1 SyncRoot : {} IsReadOnly : False IsFixedSize : True IsSynchronized : False Count : 0 |
From the spec –
If the value designated by the left operand is not a collection, the
result has type bool. Otherwise, the result is a possibly empty
unconstrained 1-dimensional array containing the elements of the
collection that test True when compared to the value designated by the
right operand.
For the second part, because the left operand is itself a bool, I think that it always be the result. This is only when the right operand is a collection.
Some examples:
1 2 3 4 5 |
$true -eq 1,2,3,4 $true -eq '','','','' $true -eq '',1,$true,$false $true -eq $null,$false,1,'' |
All of these return $true
. Conversly all of these return $false
1 2 3 4 5 6 |
$false -eq 1,2,3,4 $false -eq '','','','' $false -eq '',1,$true,$false $false -eq $null,$false,1,'' $false -eq $true,$true,$true |
The type of the left operand is very important. This wil return $true
: $false -eq 0
because the right operand is castable to the type of the left operand.