How to use string interpolation in PowerShell

By FoxLearn 10/3/2024 2:08:26 AM   82
In PowerShell, string interpolation is a convenient way to embed variables and expressions within strings.

String interpolation in PowerShell allows you to embed variables within strings, improving the readability and flexibility of your scripts. This feature simplifies your code by eliminating complex string concatenation and enabling dynamic, expressive output with custom formatting options.

This guide provides a comprehensive overview of string interpolation in PowerShell, covering all the essential concepts and techniques you need to know.

How to Use String Interpolation in PowerShell?

In PowerShell, you can use double quotes (") to create a string that supports interpolation.

$name = "Lucy"
$message = "Hello, $name!"
Write-Output $message

String interpolation in PowerShell allows you to embed expressions within strings, enabling calculations, function calls, or data manipulation directly inside the string.

# Using an expression
$message = "The sum of 2 and 3 is $((2 + 3))."
Write-Output $message

You can use curly braces to explicitly define the variable.

$name = "Lucy"
Write-Host "Do you love PowerShell, ${name}?"

When dealing with objects, you can access properties using the same interpolation technique.

$user = New-Object PSObject -Property @{ Name = "Bob"; Age = 30 }
$message = "$($user.Name) is $($user.Age) years old."
Write-Output $message

You can also use the -f operator for formatting, which can be more flexible in some cases.

$name = "Lucy"
$age = 38
$message = "{0} is {1} years old." -f $name, $age
Write-Output $message

If you need to include a dollar sign ($) or curly braces in your string without triggering interpolation, you can escape it with a backtick (`)

For example:

$message = "This costs `$7 and not `$5."
Write-Output $message

PowerShell's string interpolation only functions with double-quoted strings. If you attempt to use interpolation expressions within single-quoted strings, they will be treated as literal text and not evaluated.

For example:

$name = "John"
$message = 'Hello, ${name}!'
Write-Output $message
 
# Output: Hello, ${name}!

These techniques will help you leverage string interpolation effectively in your PowerShell scripts.