Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

powershell - Why is $false -eq "" true?

The following code segments output true:

$x = ($false -eq "") 
Write-Host $x

$x = ($false -eq 0) 
Write-Host $x

Since $false and "" are different data types, shouldn't it automatically equal false?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When doing comparison operations, PowerShell will automatically attempt to coerce the object on the right-hand side of the operator to match the type on the left-hand side.

In the case of coercing [string] to [bool], any non-null string will evaluate as $true, and a null string will evaluate as $false. See blog post Boolean Values and Operators for more information about automatic conversion of different data types to boolean values.

This sometimes leads to unexpected results:

PS C:> [bool]"$false" 

True

The string value of $false is 'False', which is a non-null string and evaluated to $true when cast back to [bool].

It also makes comparison operations non-commutative when the operands are of different data types:

PS C:> '' -eq $false
False
PS C:> $false -eq ''
True

In the first comparison the value $false is auto-cast to a string in order to match the type of the first operand (''), so you're actually comparing '' -eq 'False', which evaluates to $false.

In the second comparison the string '' is auto-cast to a boolean, again in order to match the type of the first operand ($false), so this time you're actually comparing $false -eq $false, which evaluates to $true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...