Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does '$true -eq "string"' returns $true? [duplicate]

In powerShell you compare a boolean with a string with the "-eq" operator it will always return the same boolean as I used to compare.

E.g.

$shouldBeFalse = $true -eq "hello"
$shouldBeTrue = $false -eq "hello"

The variable $shouldBeFalse is $true. The variable $shouldBeTrue is $false.

I had to use the "Equals" method:

$shouldBeFalse = $true.Equals("hello")

In this case $shouldBeFalse is $false.

But why returns the -eq operator with boolean these kind of results?

like image 738
Patrick Avatar asked Dec 14 '22 19:12

Patrick


1 Answers

PowerShell will always evaluate using the type of the left-side argument. Since you have a boolean on the left PowerShell will try and cast "Hello" as a boolean for the purpose of evaluating with -eq.

So in your case "hello" is converted to a boolean value [bool]"hello" which would evaluate to True since it is not a zero length string. You would see similar behavior if you did the opposite.

PS C:\> "hello" -eq $true
False

PS C:\> [bool]"hello" -eq $true
True

In the first case $true is converted to a string "true" which does not equal "hello" hence false. In the second case we cast "hello" to boolean so the -eq will compare boolean values. For reasons mentioned about this evaluates to True.

Another good explanation comes from this answer which might get your question flagged as a duplicate: Why is $false -eq "" true?

like image 127
Matt Avatar answered Dec 30 '22 20:12

Matt