2

The following code works as expected:

'John' | % { "$_ $_" }
> John John

However, I couldn't work out a way of storing the string $_ $_ in a variable, which is later used in the pipeline:

$f = '$_ $_'
'John' | % { $f }
> $_ $_

How would I "interpolate" a variable, instead of using double quoted string?

2 Answers 2

5

You can define a PowerShell ScriptBlock, enclosed in curly braces, and then execute it using the . call operator.

$f = { $_ $_ }
'John' | % { . $f }

Output looks like:

John
John

Or, if you want a single string (like your initial question), you can do:

$f = { "$_ $_" }
'John' | % { . $f };

Output looks like:

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

2 Comments

Why is the semi-colon needed in the second example?
The semicolon is not a requirement, but it delimits the end of a command in PowerShell.
4

The answer is

'John' | % { $ExecutionContext.InvokeCommand.ExpandString($f) }
> John John

Credit goes to Bill_Stewart for his answer to PowerShell Double Interpolation.

Comments

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.