1

Consider this bit of PowerShell:

PS> $x = 'y'
PS> ($x = 'y')
y

Why does adding the parens cause the value to get printed?

EDIT: Some more interesting cases:

 PS> $z = ($x = 'y')
 PS> $z
 y
 PS> $( $x = $y )
 PS> $z = $( $x = $y )
 PS> $z
Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168

2 Answers2

2

parentheses tell the shell to evaluate the value within the parentheses first then print the result. in your first command, it's assignment; However, the second is a command that will be evaluated and print the result, namely 'y'

update

PS> $z = ($x = 'y') # assignment, no print , ($x = 'y') returns 'y'
PS> $z    
y
PS> $( $x = $y ) # this is a voidable expression whose result is discarded when used directly as a statement. so, $( $x = $y ) -eq $null
PS> $z = $( $x = $y ) # same to above
PS> $z

"PowerShell in Action" states difference between the subexpression construct and simple parentheses is how voidable statements are treated. ++,--,+=,-= operations are treated as voidable statement either.

In simple parentheses (), voidable statements is not discarded, but in subexpression $(), they are discarded.

Jackie
  • 2,476
  • 17
  • 20
1

Expressions with side effects don't normally return their result when used as a statement. For example:

PS> $x = $a++

Clearly, $a++ must have a value for this to work. However:

PS> if (...) $a++

you don't want this to print out the value of $a. So the result is discarded.

Grouping parentheses override this behavior, and force the result to be returned to the pipeline, even if it's voidable:

PS> ($x = 'y')
'y'

On the other hand, to void a non-voidable expression, either cast it to void or pipe it to Out-Null:

PS> mkdir Foo | Out-Null
PS> [void](mkdir Bar)

Resources

SO question Why it needs an extra pair of bracket?

The Windows PowerShell Language Specification - 7.1.1 Grouping parentheses, but they don't use the "voidable expression" terminology.

Blog post PowerShell ABC's - V is for Voidable Statements

Community
  • 1
  • 1
Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
  • "voidable expression" is used by 'PowerShell in Action', whose author is in charge of powershell in MS. I just copied it. :-) – Jackie Nov 02 '12 at 07:31
  • Link for [PowerShell ABC's - V is for Voidable Statements](https://devcentral.f5.com/s/articles/powershell-abcs-v-is-for-voidable-statements) has changed. – Chris Oldwood Jan 15 '20 at 17:02