In PowerShell, operator overloading is determined by the left-hand side (lhs) argument.
This means that when you supply a string as the lhs argument, the parser will attempt to convert the right-hand side (rhs) to a string as well.
When cast to a string, $true
comes out as the string "True" - which, since PowerShell's string comparison operators are all case-insensitive by default, happens to equal "true".
This operation:
'true' -eq $true
Is interpreted as
'true' -eq 'True'
Which happens to be $true
, satisfying your if
condition.
With $true
, this also happens to work the other way around, because a non-empty string, when converted to a boolean, evaluates to $true
:
In other words
$true -eq 'true'
Is interpreted as
$true -eq $true
This can lead to confusion, since the string "false" will incidentally also be evaluated as $true
, simply because the string "false" is not empty:
PS C:> $true -eq "true"
True
PS C:> $true -eq "false"
True
PS C:> $true -eq ""
False
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…