Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell string interpolation syntax

I always used the following syntax to be sure that variable were expanded in a string:

"my string with a $($variable)"

I recently ran into the following syntax:

"my string with a ${variable}"

Are they equivalent? Any difference?

like image 546
fra Avatar asked Feb 20 '20 15:02

fra


People also ask

How do I interpolate a string in PowerShell?

String Interpolation Using a Subexpression Operator in PowerShell. In Windows PowerShell, we can use the subexpression operator $() to run an expression within an expression like string interpolation.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What is ${} in PowerShell?

The ${} notation actually has two uses; the second one is a hidden gem of PowerShell: That is, you can use this bracket notation to do file I/O operations if you provide a drive-qualified path, as defined in the MSDN page Provider Paths.

How to connect string using string interpolation in PowerShell?

Let’s understand with an example to connect string using string interpolation in PowerShell. $company variable contains ShellGeek string value. In the next statement, inside double quotes, PowerShell interpolates the string variable name and displays the result as below

What is the use of PowerShell in PowerShell?

PowerShell allows you to do command execution inside the string with a special syntax. This allows us to get the properties of these objects and run any other command to get a value.

How to interpolate environment variable with its value in string?

Let’s consider an example to interpolate environment variable with its value in the string as below $env: COMPUTERNAME in double-quotes display a variable value and concatenate it with a string. There are certain cases where putting a variable inside double-quotes doesn’t provide results as expected.

How to use variables in PowerShell strings?

PowerShell has another option that is easier. You can specify your variables directly in the strings. $message = "Hello, $first $last." The type of quotes you use around the string makes a difference.


3 Answers

To complement marsze's helpful answer:

${...} (enclosing the variable name in { and }) is indeed always necessary if a variable name contains special characters, such as spaces, ., or -.

  • Not special are _ and - surprisingly and problematically - ?.
  • Note: : is invariably interpreted as terminating a PowerShell drive reference, in the context of namespace variable notation, or a scope specifier, irrespective of whether {...} enclosure is used or required (e.g., in $env:USERNAME or ${env:USERNAME}, env refers to the PowerShell drive representing all environment variables; in $script:foo or ${script:foo}, script refers to the script's scope and its variables).

Note:

  • ${...} - the syntax for disambiguating a variable name - is not to be confused with $(...), which is the subexpression operator, needed to embed any expression or command that goes beyond a stand-alone variable reference in an expandable string ("..."). As such, the two syntax forms are independent of one another and may need to be combined in a given situation; e.g. "$var" / "${var}" work fine, but "$var.someProperty" / "${var}.someProperty" do not: you need "$($var.someProperty)" / "$(${var}.someProperty)"

In the context of string expansion (interpolation) inside "...", there is another reason to use ${...}, even if the variable name itself doesn't need it:

If you need to delineate the variable name from directly following non-whitespace characters, notably including ::

$foo = 'bar'  # example variable

# INCORRECT: PowerShell assumes that the variable name is 'foobarian', not 'foo'
PS> "A $foobarian."
A .  # Variable $foobarian doesn't exist -> reference expanded to empty string.

# CORRECT: Use {...} to delineate the variable name:
PS> "A ${foo}barian."
A barbarian.

# INCORRECT: PowerShell assumes that 'foo:' is a *namespace* (drive) reference
#            (such as 'env:' in $env:PATH) and FAILS:
PS> "$foo: bar"
Variable reference is not valid. ':' was not followed by a valid variable name character. 
Consider using ${} to delimit the name.

# CORRECT: Use {...} to delineate the variable name:
PS> "${foo}: bar"
bar: bar

See this answer for a comprehensive overview of PowerShell string-expansion rules.

Note that you need the same technique when string expansion is implicitly applied, in the context of passing an unquoted argument to a command; e.g.:

# INCORRECT: The argument is treated as if it were enclosed in "...",
#            so the same rules apply.
Write-Output $foo:/bar

# CORRECT
Write-Output ${foo}:/bar

Finally, a somewhat obscure alternative is to `-escape the first character after the variable name, but the problem is that this only works as expected with characters that aren't part of escape sequences (see about_Special_Characters):

# OK: because `: is not an escape sequence.
PS> "$foo`: bar"
bar: bar

# NOT OK, because `b is the escape sequence for a backspace character.
PS> "$foo`bar"
baar # The `b "ate" the trailing 'r' of the variable value
     # and only "ar" was the literal part.
like image 113
mklement0 Avatar answered Oct 19 '22 10:10

mklement0


${variable} is the syntax for variable names that include special characters.

(See about_Variables -> Variable names that include special characters )

Example:

${var with spaces} = "value"
"var with spaces: ${var with spaces}"

So in your case it's basically the same as simply writing $variable

like image 40
marsze Avatar answered Oct 19 '22 09:10

marsze


Note that $() is helpful for json objects:

"My json property is $($jsonObj.property)"
like image 13
derekantrican Avatar answered Oct 19 '22 10:10

derekantrican