PowerShell - 产生多个结果的 if 语句条件 [英] PowerShell - if statement condition that produces multiple results

查看:106
本文介绍了PowerShell - 产生多个结果的 if 语句条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个愚蠢的例子:

Please consider this silly example:

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

以上产生的输出 true.

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

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.

推荐答案

如预期的那样,以上产生的输出为 true.

The above produces the output true, as expected.

为什么你期望它输出true"?

Why do you expect it to output "true"?

if 语句如何处理这种由条件输出多个值的情况?

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).

代码

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

等于

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

等于

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

表现为

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

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

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

例如,以下内容不会打印true":

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.

所以

   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

这篇关于PowerShell - 产生多个结果的 if 语句条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆