1

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I accepted the answer with {} syntax as it seems to shorter, but upvoted your too.
5

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" 

1 Comment

Thanks, minor correction: as I tried to find out, I experienced that not only space, but anything what does not qualify as legal character in variable name, like .,/( etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.