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

a 夏天 提交于 2019-11-29 07:46:58
Matt

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?

BusyBeingDelicious

$TRUE is > 0 and "hello" length > 0 so it is TRUE. $FALSE is == 0 and "hello" length < 0 so it is FALSE.

When you use Equals, the var are compared as strings, so $TRUE isn't equal to hello -> FALSE.

source: http://blogs.msdn.com/b/powershell/archive/2006/12/24/boolean-values-and-operators.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!