Expanding Variables in Strings

by Feb 26, 2014

To insert a variable into a string, you probably know that you can use double quotes like this:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$domain\$username"

This works well as long as it is clear to PowerShell where your variables start and end. Check this out:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$username: located in domain $domain"

This fails, because PowerShell adds the *** to the variable (as indicated by the token colors).

You can use the PowerShell backtick escape character to escape special characters like the ***:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$username`: located in domain $domain"

This will not help you, though, if the problem was not caused by a special character in the first place:

"Current Background Color: $host.UI.RawUI.BackgroundColor" 

Token colors indicate that double quoted strings only resolve the variable and nothing else (nothing that follows the variable name, like accessing object properties).

To solve this problem, you must use one of these techniques:

"Current Background Color: $($host.UI.RawUI.BackgroundColor)"
'Current Background Color: ' + $host.UI.RawUI.BackgroundColor
'Current Background Color: {0}' -f $host.UI.RawUI.BackgroundColor

Twitter This Tip! ReTweet this Tip!