1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tahir Hassan
  • 5,715
  • 6
  • 45
  • 65

2 Answers2

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
3

The answer is

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

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

Community
  • 1
  • 1
Tahir Hassan
  • 5,715
  • 6
  • 45
  • 65