Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "$($var)" and ("$var") in PowerShell

Tags:

powershell

Can anyone tell me what difference, if any, there is between the following PowerShell commands:

Set-ItemProperty -Path "$($var)" -Name $var2 -Value $var3

and

Set-ItemProperty -Path ("$var") -Name $var2 -Value $var3

$var is a registry location, i.e. HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion...

I have also seen both used for the Path parameter in New-ItemProperty

like image 804
FrinkTheBrave Avatar asked Mar 04 '23 07:03

FrinkTheBrave


1 Answers

"$($var)" outputs the value of the variable $var in a subexpression and then puts that output in a string. The string is then used as an argument in the Set-ItemProperty statement.

("$var") puts the value of the variable $var in a string and evaluates that in a grouping expression (similar to subexpression, but doesn't allow multiple statements). The output from the grouping expression (which in this case is the string) is then passed as an argument in the Set-ItemProperty statement.

Neither is required in your example statement. Using the variable by itself is sufficent.

Set-ItemProperty -Path $var -Name $var2 -Value $var3

You'd use a subexpression ($(...)) in a string if you want to insert something other than a simple variable into a string that has other text as well, e.g. the output of another statement:

"foo $(Get-Date) bar"

the value of an object property:

"foo $($var.Foo) bar"

or an element of an array:

"foo $($var[5]) bar"

because these cannot be used directly in a string otherwise. If you need to insert the value of a variable into a string you can do that without a subexpression:

"foo ${var} bar"

You'd use a grouping expression ((...)) if you want the output of an expression used as the argument of the statement:

Do-Something -Foo (Get-Date)

Putting just a string into a subexpression doesn't make any sense.

like image 54
Ansgar Wiechers Avatar answered Mar 12 '23 09:03

Ansgar Wiechers