PowerShell: The difference in parentheses expressions PowerShell: The difference in parentheses expressions powershell powershell

PowerShell: The difference in parentheses expressions


For the array and subexpression operators, the parentheses are simply needed syntactically. Their only purpose is to wrap the expression the operator should be applied on.

Some examples:

# 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 })

When you put (only) parentheses around a variable assignment, this is called variable squeezing.

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

You can get the pass-thru version for all your examples by combining variable squeezing with the subexpression operator syntax (that is, adding a second pair of parentheses):

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


$( ) is unique. You can put multiple statements inside it:

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

You can also put things you can't normally pipe from, like foreach () and if, although the values won't come out until the whole thing is finished. This allows you to put multiple statements anywhere that just expects a value.

$(foreach ($i in 1..5) { $i } ) | measure | % count5
$x = 10if ( $( 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