Tahir Hassan
Tahir Hassan

Reputation: 5817

PowerShell string interpolation via a variable

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?

Upvotes: 2

Views: 3475

Answers (2)

user189198
user189198

Reputation:

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

Upvotes: 5

Tahir Hassan
Tahir Hassan

Reputation: 5817

The answer is

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

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

Upvotes: 4

Related Questions