Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 643
KevinD Avatar asked Nov 28 '12 22:11

KevinD


People also ask

What is mean by $_ in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3. 0; Usage information found here) which represents the current item from the pipe.

What does $() mean in PowerShell?

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

What does @{ mean in PowerShell?

In PowerShell V2, @ is also the Splat operator. PS> # First use it to create a hashtable of parameters: PS> $params = @{path = "c:\temp"; Recurse= $true} PS> # Then use it to SPLAT the parameters - which is to say to expand a hash table PS> # into a set of command line parameters.

What is a string type variable in PowerShell?

A variable is a unit of memory in which values are stored. In PowerShell, variables are represented by text strings that begin with a dollar sign ( $ ), such as $a , $process , or $my_var .


1 Answers

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

like image 59
Amith George Avatar answered Oct 27 '22 20:10

Amith George