String Interpolation in Powershell Strings

I've been re-learning PowerShell lately.

String Delimiters


There are two string delimiters available for building strings in PowerShell: apostrophe (') and double quote ("):

Write-Host 'Hello World'
Write-Host "Hello World"


Both of these PowerShell commands send the string

Hello World

to the console.

I fell into the habit of using the apostrophe in my PowerShell scripts, and found that I missed string interpolation that I use so often in C# and PHP.

Consider the following example:

$name='Rick'
$distanceInMiles=10

$greeting = 'Hello, my name is '+$name+' and I work '+$distanceInMiles+' miles from home.'
Write-Host $greeting


When this script is executed, the following is written to the console:

Hello, my name is Rick and I work 10 miles from home.

String Interpolation


String interpolation lets you embed expressions into a string when defining the string. The expressions are evaluated when the string is created. It can make a string definition simpler and cleaner by removing the concatenation code ( '+variable_name+' ...)  from the string.

I made the following change to embed $name and $distanceInMiles directly into the string:

# does not interpolate
$greeting = 'Hello, my name is $name and I work $distanceInMiles miles from home.'


I expected to see:

Hello, my name is Rick and I work 10 miles from home.

But I saw:

Hello, my name is $name and I work $distanceInMiles miles from home.

With a little BinGoogling I found the answer: to use string interpolation in PowerShell, you have to use the double quote string delimiter, instead of the apostrophe.

I made the following changes (highlighted in yellow):

$greeting = "Hello, my name is $name and I work $distanceInMiles miles from home."


This change gave me the output I was expecting.

One Last Thing


You may be wondering why I emphasized the phrase "when the string is created."

String interpolation evaluates the embedded expressions using the values of the expressions at the time the string is created. Once it is created, changing the variables used in the embedded expressions does not change the interpolated string.

Consider the following:

$name='Rick'
$greeting = "Hi, my name is $name"
$name='Bob'


Write-Host $greeting


Even though the third line of the script changed the value of $name from 'Rick' to 'Bob', This script will send

Hello, my name is Rick

to the console, because the expressions are evaluated at the time $greeting is created, not when the value of $greeting is first used.

 Happy Coding!

Comments

Popular posts from this blog

Using Linq To XML to Parse XML with Multiple Namespaces