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