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
"$($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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With