views:

142

answers:

1

Curious, what is the idea behind this:

@() -as [bool]
# False

@($null) -as [bool] 
# False

@($null, $null) -as [bool]
# True

I would expect either False/True/True or False/False/False, but not False/False/True.

+6  A: 

As outlined in the Powershell Quick reference¹:

True                                                 False 
~~~~                                                 ~~~~~
$TRUE                                                $FALSE 
Any string of length > 0, except the word “false”    Empty string or the string “false” 
Any number ≠ 0                                       Any number = 0 
Array of length > 1                                  Array of length 0 
Array of length 1 whose element is true              Array of length 1 whose element is false 
A reference to any object                            Null 

I think the idea behind it was that an array with just one element $false can easily happen if you put the output of a cmdlet/function into an array. You might expect more values but some error made it to return $false, but $false twice in the array might be unlikely in that case.

Or maybe we should wait for Jeffrey Snover to answer here :-)

¹ C:\Windows\System32\WindowsPowerShell\v1.0\Documents\en-US\QuadFold.rtf on my machine

Joey
Allright with the quote, but what is the idea behind this behaviour ? Can you give an example ?
Cédric Rup
Was a use-case I haven't encountered so far. off the top of my head I can't give a convincing example, sorry. Most things I recently did in PS was solving Project Euler problems and that's hardly the proper domain for that language :-) But I'll think about it, maybe I'll find a convincing example.
Joey
This citate spawned a new question... "Empty string or the string “false”" but I see True trying "false" -as [bool]. And a minor typo "Array of length > 0", it should be "Array of length > 1" as I see in my .rtf.
alex2k8
Same behaviour as alex2k8 here, using V2 CTP3...Maybe the idea behind the array thing is to ease thing when a @() operator is used (i.e, getting a more direct result/hint when the response of a cmdlet in forced to an array) , but this explanation looks pretty shallow ;o)
Cédric Rup
Hmm, right, seeing the same in V2 CTP3 here. Maybe they changed that bit; don't have access to V1 currently.
Joey
It looks like a formal rule, so accepting the answer.
alex2k8