g.pickardou
g.pickardou

Reputation: 35873

How to create PowerShell string interpolation when legal variable character follows the variable in the string?

I try to use string interpolation in PowerShell:

$myvariable = "World"
Write-Host "Hello $myvariable" 

The code above works fine, writes "Hello World"

However in case if in the string the character follows the variable part forms a legal variable name, it cannot be parsed because of the ambiguity

$myvariable = "World"
Write-Host "Hello $myvariableimmediately continuing" 

Question

I understand this should not work, but despite of googling I can not find such an example. What is the syntax I miss?

Upvotes: 1

Views: 1022

Answers (2)

LeeM
LeeM

Reputation: 1248

If you want run-on text to your variable, you can do it like this:

Write-Host "Hello $($myvariable)immediately continuing"

Hello Worldimmediately continuing

The $($variable) construction is also useful if your object is multivalued and you just want to write out one value.

Write-host "My cat's name is $($cat.name) and he is $($cat.age) years old"

The parentheses are operating in basically the same way they do in mathematics - the expression inside is evaluated first, and then the result is parsed with rest of the statement.

Upvotes: 7

harper
harper

Reputation: 13690

The space is only one way to end a variable name.You can use brackets to exactly define the length of a variable in a string.

$myvariable = "World"
Write-Host "Hello ${myvariable}immediately continuing" 

Upvotes: 5

Related Questions