PowerShell Logic PowerShell Logic powershell powershell

PowerShell Logic


I like fundamental questions about the behavior and features of the language like this... Give's me an excuse to read the PowerShell language specification.

You can download said specification: 2.0 and 3.0. See section 7.8.1 - Equality and relational operators.

For the first part of the question, something actually is returned - an empty array, which is illustrated by: ($false,$false -eq $true).psbase

Length         : 0LongLength     : 0Rank           : 1SyncRoot       : {}IsReadOnly     : FalseIsFixedSize    : TrueIsSynchronized : FalseCount          : 0

From the spec -

If the value designated by the left operand is not a collection, the result has type bool. Otherwise, the result is a possibly empty unconstrained 1-dimensional array containing the elements of the collection that test True when compared to the value designated by the right operand.

For the second part, because the left operand is itself a bool, I think that it always be the result. This is only when the right operand is a collection.

Some examples:

$true -eq 1,2,3,4$true -eq '','','',''$true -eq '',1,$true,$false$true -eq $null,$false,1,''

All of these return $true. Conversly all of these return $false

$false -eq 1,2,3,4$false -eq '','','',''$false -eq '',1,$true,$false$false -eq $null,$false,1,''$false -eq $true,$true,$true

The type of the left operand is very important. This wil return $true: $false -eq 0 because the right operand is castable to the type of the left operand.


Best guess:

It's evaluating as True because it's an array with more than one member. An array does not have a ToBoolean() method.

As long as it's a scalar, or an array with only has one member Powershell can coerce that to a scalar and get to a ToBoolean() method on the member. As soon as it goes to 2 or more, it always returns True, regardless of what the elemets are. If there's no ToBoolean(), and it falls back to the default ToString() method, that's always going to evaluate to True.

Or maybe not.


Perhaps the -eq operator is evaluating their existence (aka not $null) rather than their value.

Similar to the IF statement perhaps?

PS> if("anyval"){$true}else{$false}True

This answer provided by @Joey might also prove useful.