Powershell 5.1 三元数组赋值

Powershell 5.1 ternary with array assignment

我对 Powershell 5.1 中的三元运算符有疑问。如果我尝试分配数组 @(...):

,它不会像我预期的那样工作
    # I can assign an array to a variable:
    $a=@("TRUE")
    write-host "a:" $a
    
    # I can do that in a proper if/then statement, too:
    $b = @(if ($false) {@("True")} else {@("False")})
    write-host "b:" $b
    
    # Assignment of string constants works fine with ternary syntax:
    $c = @( {"True"} , {"False"} )[!$true]
    write-host "c:" $c
    
    # but not with array assignments:
    $d = @( {@("True")} , {@("False")} )[!$false]
    write-host "d:" $d
    # Expected: "False". 
    # Actual output: @("False")

输出:

a: TRUE
b: False
c: "True"
d: @("False")

关于三元运算符的帖子没有为我阐明这一点。 (Ternary operator in PowerShell)

更新: $d 需要是一个数组,以及两个内部项目。为简单起见,此处只显示了一个字符串常量。

注:

  • PowerShell (Core) 7+ 现在有一个 built-in 三元运算符,这样你就可以使用类似 $var = $true ? "True" : "False"

不要在操作数周围使用 { ... }{ ... } 用于 script-block 文字 ,其计算结果为 [=42= 字符串上下文.

中的]逐字内容(不带分隔符)

省略封闭的 {} 解决了眼前的问题:

$d = @( @("True") , @("False") )[!$false]
write-host "d:" $d

然而,使用@()array-subexpression operator似乎既多余又无效,这取决于你的意图;以上相当于:

$d = ( "True", "False" )[!$false]
write-host "d:" $d

请注意,对于数组 文字 @(...) 永远不会 需要 ;使用 ,array constructor operator, is generally sufficient. See the middle section of 了解更多信息。

如果你想让$d成为一个数组,你需要将@(...)应用到整个表达式:

# $d is now a 1-element array containing 'False'
$d = @(( "True", "False" )[!$false])
write-host "d:" $d

或者,type-constrain $d 为数组:

# $d is now a 1-element array containing 'False'
[array] $d = ( "True", "False" )[!$false]
write-host "d:" $d