powershell variable syntax $($a)?
$()
is a subexpression operator. It means "evaluate this first, and do it separately as an independent statement".
Most often, its used when you're using an inline string. Say:
$x = Get-ChildItem C:\;
$x | ForEach-Object {
Write-Output "The file is $($_.FullName)";
}
Compare that to:
$x = Get-ChildItem C:\;
$x | ForEach-Object {
Write-Output "The file is $_.FullName";
}
You can also do things like $($x + $y).ToString()
, or $(Get-Date).AddDays(10)
.
Here, without the subexpression, you'd get $a:\calendar
. Well, the problem there is that the colon after a variable is an operator. Specifically, the scope operator. To keep PowerShell from thinking you're trying to look for a variable in the a
namespace, the author put the variable in a subexpression.
As far as I've been able to tell using PS for the past few years, parentheses without the dollar sign are also essentially subexpressions. They won't be evaluated as a subexpression when within a string, but otherwise they usually will. It's kind of a frustrating quirk that there's no clear difference.
The $()
is the subexpression operator. It causes the contained expressions to be evaluated and it returns all expressions as an array (if there is more than one) or as a scalar (single value). Plain parentheses ()
are simply the mathematical precedence operator and therefore just work in arithmetic expressions to give precedence
Notably, $()
is interpreted within a string, whereas ()
will be just be taken literally - it has no special meaning. So the following:
$a = "Hello"
"$($a.Length)"
gives
5
whereas
"($a.Length)"
gives
"(Hello.Length)"
As I said, the $()
can consist of multiple expressions, all of which are returned as output. ()
does not do this. So this is an error as the contents are not an arithmetic expression:
(1;2)
whereas this
$(1;2)
evaluates to an array and outputs:
1
2
The expression $($a) is evaluated before the application of the trailing scope :
operator and prevents the scope being applied directly to a
, instead $a
is evaluated first and then the scope is applied.