What does $($variableName) mean in expandable strings in PowerShell?

KevinD picture KevinD · Nov 28, 2012 · Viewed 27.4k times · Source

I've seen a number of example scripts online that use this. Most recently, I saw it in a script on automating TFS:

[string] $fields = "Title=$($taskTitle);Description=$($taskTitle);Assigned To=$($assignee);"
$fields += "Area Path=$($areaPath);Iteration Path=$($iterationPath);Discipline=$($taskDisciplineArray[$i]);Priority=$($i+1);"
$fields += "Estimate=$($taskEstimateArray[$i]);Remaining Work=$($taskRemainingArray[$i]);Completed Work=$($tasktaskCompletedArray[$i])"

From what I can tell, $($taskTitle) seems to be equivalent to $taskTitle. Am I missing something? Is there any reason to use the parentheses and extra dollar sign?

Answer

Amith George picture Amith George · Nov 28, 2012

The syntax helps with evaluating the expression inside it.

$arr = @(1,2,3)

$msg1 = "$arr.length"
echo $msg1 # prints 1 2 3.length - .length was treated as part of the string

$msg2 = "$($arr.length)"
echo $msg2 # prints 3

You can read more at http://ss64.com/ps/syntax-operators.html