Why does the string $ true -eq "" return $ true?
In powerShell, you are comparing a boolean to a string with the "-eq" operator, it will always return the same boolean as before.
eg.
$shouldBeFalse = $true -eq "hello"
$shouldBeTrue = $false -eq "hello"
The $ shouldBeFalse variable is $ true. The variable $ shouldBeTrue is $ false.
I had to use the Equal To method:
$shouldBeFalse = $true.Equals("hello")
In this case, $ shouldBeFalse is $ false.
But why does the -eq operator return with boolean results?
source to share
PowerShell will always evaluate using the left side argument type. Since you have a boolean on the left, PowerShell will try to apply "Hello" as a boolean to evaluate with -eq
.
So in your case it is "hello"
converted to a boolean value [bool]"hello"
which will evaluate to True as it is not a zero length string. If you did the opposite, you will see similar behavior.
PS C:\> "hello" -eq $true
False
PS C:\> [bool]"hello" -eq $true
True
In the first case, it is $true
converted to the string "true", which is not equal to "hello", hence false. In the second case, we add "hello" to boolean, so it -eq
will compare booleans. For the reasons mentioned, this evaluates to True.
Another good explanation comes from this answer, which may pose your question as a duplicate: Why is $ false -eq "" correct?
source to share
$TRUE
> 0
and "hello" length > 0
therefore TRUE
$FALSE
== 0
and "hello" length < 0
therefore this FALSE
.
When you use Equals, variables are compared as strings, so $TRUE
not equal hello → FALSE
.
source: http://blogs.msdn.com/b/powershell/archive/2006/12/24/boolean-values-and-operators.aspx
source to share