PowerShell String Interpolation (Variables in Strings)

PowerShell string interpolation means writing a variable straight into a double-quoted string, and PowerShell swaps in its value when the line runs. Wrap anything more than a plain variable in $():

$name = 'Maria Lopez'
$price = 49.99
"Hello, $name! Two items cost $($price * 2) USD."

In this tutorial, I’ll build an order message for a small online store, one step at a time, and hit every trap on the way. I tested each example in PowerShell 7.6 and Windows PowerShell 5.1.

What Is String Interpolation in PowerShell?

Double quotes make an expandable string, so PowerShell replaces each $name with its value. Single quotes make a verbatim string, and nothing gets replaced:

$name = 'Maria Lopez'
$city = 'Austin'
"Order for $name ships to $city."
'Order for $name ships to $city.'
"The `$name variable holds $name."

Output:

Order for Maria Lopez ships to Austin.
Order for $name ships to $city.
The $name variable holds Maria Lopez.

The backtick in the last line stops one substitution, so `$name prints as text. The full story of single vs. double quotes in PowerShell covers a few more cases.

If you only need a value on screen, you don’t need a string at all. These ways to print a variable in PowerShell work fine.

Step 1: Use $() for Properties, Indexes and Math

Here’s the trap that catches almost everyone. Only a plain variable expands. A dot or a bracket after it is treated as ordinary text:

$order = [pscustomobject]@{ Customer = 'Dana Reyes'; Total = 89.99 }
$stores = 'Austin', 'Denver', 'Seattle'
"Customer: $order.Customer"
"Customer: $($order.Customer)"
"First store: $stores[0]"
"First store: $($stores[0]) of $($stores.Count)"
"Two orders: $($order.Total * 2) USD"
"Shout: $($order.Customer.ToUpper())"

Output:

Customer: @{Customer=Dana Reyes; Total=89.99}.Customer
Customer: Dana Reyes
First store: Austin Denver Seattle[0]
First store: Austin of 3
Two orders: 179.98 USD
Shout: DANA REYES
PowerShell string interpolation needs a subexpression for object properties and array indexes
“$order.Customer” prints the whole object, “$($order.Customer)” prints the name (PowerShell 7)

$order.Customer printed the whole object followed by “.Customer”, and $stores[0] printed all three stores plus “[0]”. Wrapping them in $() fixed both.

A subexpression runs any code you like: math, method calls, even a whole if statement in PowerShell. Both versions printed the same output.

$n = 3
"You have $n item$(if ($n -ne 1) { 's' })"

Output:

You have 3 items

Why Does “$city:” Throw an Error?

Put a colon right after a variable name and PowerShell reads it as a drive or scope prefix, like $env:. The script doesn’t run at all:

$city = 'Denver'
"$city: 3 orders shipped"

Output:

ParserError: C:\psfaqs\sicolon.ps1:2
Line |
   2 |  "$city: 3 orders shipped"
     |   ~~~~~~
     | Variable reference is not valid.