$()
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…