PowerShell - if statement condition that produces multiple results

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

Please consider this silly example:

if (1..3) { "true" } 

The above produces the output true.

My question: How does the if statement handle a case like this where multiple values are output by the conditional? Is the "true" output the result of the "3" (the last case)? Or is some other logic at work? Thanks.

回答1:

The above produces the output true, as expected.

Why do you expect it to output "true"?

How does the if statement handle a case like this where multiple values are output by the conditional?

The conditional does not "output" any values. It always evaluates to "true" or "false". The question remaining is, why does it evaluate to true (or false).

The code

   if (1..3) { "true" } 

is equal to

   if (@(1,2,3)) { "true" } 

is equal to

   $array = @(1,2,3)    if ($array) { "true" } 

behaves as

   if ($array.Length -gt 0) { "true" } 

So not individual elements are tested, but rather if the array contains any elements.

For example, the following will not print "true":

   if (@()) { "true" } 

Update If the array contains only one value, it looks (I coudn't find any normative documentation on that), as if the array is treated as a scalar value using the one element inside.

So

   if (@(0))     if (@(0.0))     if (@(1))     if (@(-1))     if (,$null))     if (,"false"))  

is treated as

   if (0)  --> false    if (0.0)  --> false    if (1)  --> true    if (-1)  --> true    if ($null)  --> false    if ("false") --> true 


回答2:

The observed behavior is explained (to some extent) in this blog post. Basically, if an expression evaluates to 0 it's interpreted as false, otherwise as true. Examples:

0      => False 1      => True "0"    => True (because it's a string of length 1) ""     => False (because it's a string of length 0) @()    => False @(0)   => False (this one's a little surprising) @(0,1) => True @("0") => True 


回答3:

1..3 results in an array with 3 items

PS> (1..3).GetType()  IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     Object[]                                 System.Array  PS> (1..3).Length 3 

If there is at least one item in the array the if considers it true

PS> if (@()) { "true" } else { "false" } false  PS> if (@(1)) { "true" } else { "false" } true  PS> if (@(1,2)) { "true" } else { "false" } true 


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