PowerShell:括号表达式的区别

PowerShell: The difference in parentheses expressions

我一直在试验 operators/expressions 的不同形式,包括括号,但我找不到对我 运行 参与的交互的解释。即,( )$( )(子表达式运算符)不是等价的。它也不等同于 @( )(数组运算符)。在大多数情况下,这无关紧要,但是当尝试将括号的内容作为表达式(例如,变量赋值)求值时,它们是不同的。我正在寻找一个关于 what 括号在做什么的答案,当它们不是明确的一个或另一个运算符并且 about_ 文档没有指出这一点时。


($var = Test-Something) # -> this passes through
$($var = Test-Something) # -> $null
@($var = Test-Something) # -> $null

about_Operators

对于 array and subexpression 运算符,括号只是语法上需要的。它们的唯一目的是包装应该应用运算符的表达式。

一些示例:

# always return array, even if no child items found
@(Get-ChildItem -Filter "*.log").Count

# if's don't work inside regular parentheses
$(if ($true) { 1 } else { 0 })

当您(仅)在变量赋值周围放置括号时,这称为 variable squeezing

$v = 1 # sets v to 1 and returns nothing
($v = 1) # sets v to 1 and returns assigned value

通过将变量压缩与子表达式运算符语法(即添加第二对括号)相结合,您可以获得所有示例的 pass-thru 版本:

($var = Test-Something)
$(($var = Test-Something))
@(($var = Test-Something))

$( ) 是独一无二的。您可以在其中放置多个语句:

$(echo hi; echo there) | measure | % count

2

您还可以放入您通常无法通过管道传输的内容,例如 foreach () 和 if,尽管在整个流程完成之前不会得出值。这允许您将多个语句放在任何只需要一个值的地方。

$(foreach ($i in 1..5) { $i } ) | measure | % count

5
$x = 10
if ( $( if ($x -lt 5) { $false } else { $x } ) -gt 20)
{$false} else {$true}
for ($i=0; $($y = $i*2; $i -lt 5); $i++) { $y }
$err = $( $output = ls foo ) 2>&1