PowerShell:
Interpolating a string

How to:

In PowerShell, you interpolate with double-quoted strings and the $ symbol before the variable name. Wrap expressions in $() to evaluate them right inside the string.

$name = "Alex"
$day = (Get-Date).DayOfWeek

# Basic variable interpolation
"Hello, $name! Happy $day!"

# Expression interpolation
"Pi to two decimal places is $(Math::Round([Math]::Pi, 2))"

# Output
Hello, Alex! Happy Wednesday!
Pi to two decimal places is 3.14

Deep Dive

PowerShell adopted string interpolation borrowing from earlier programming languages like Perl. Before PowerShell v3, we concatenated with the + operator or used the -f format operator. Here’s the evolution:

  • Old-school concatenation: "Hello, " + $name + "! It's " + $day + "."
  • Format operator: "Hello, {0}! It's {1}." -f $name, $day

Interpolated strings are easier to read and less error-prone. Under the hood, PowerShell interprets the interpolated string and replaces variables or expressions with their values when the string is evaluated, not when it’s defined.

See Also