PowerShell - if语句条件产生多个结果

时间:2013-06-13 09:53:26

标签: powershell

请考虑这个愚蠢的例子:

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

以上产生输出 true

我的问题:if语句如何处理这样的情况,其中条件输出多个值? “真实”输出是“3”(最后一种情况)的结果吗?还是其他一些逻辑在起作用?感谢。

3 个答案:

答案 0 :(得分:4)

this blog post中解释(在某种程度上)观察到的行为。基本上,如果表达式求值为0,则将其解释为false,否则为true。例子:

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

答案 1 :(得分:2)

  

上面按预期产生输出true。

为什么期望它输出“true”?

  

if语句如何处理这样的情况,其中条件输出多个值?

条件不会“输出”任何值。它总是评估为“真”或“假”。剩下的问题是,为什么评估为真(或假)。

代码

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

等于

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

等于

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

表现为

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

因此,不测试单个元素,而是测试数组是否包含任何元素。

例如,以下打印“true”:

   if (@()) { "true" }

更新如果数组只包含一个值,那么看起来(我找不到任何规范性文档),就像数组被视为标量一样使用里面的一个元素的值。

所以

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

被视为

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

答案 2 :(得分:1)

1..3会产生一个包含3个项目的数组

PS> (1..3).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS> (1..3).Length
3

如果数组中至少有一个项目,那么if认为是真的

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

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

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