powershell: interpolated string is not being evaluated

Solution 1:

The incidental problem with your code is that you're defining your string template, $o0, only after you're trying to use it.

  • This problem was masked by the ISE's unfortunate behavior of effectively dot-sourcing script invocations. i.e. executing them in the same scope during repeated invocations, which can have side effects.

  • As an aside: The PowerShell ISE is no longer actively developed and there are reasons not to use it (bottom section), notably not being able to run PowerShell (Core) 6+. The actively developed, cross-platform editor that offers the best PowerShell development experience is Visual Studio Code with its PowerShell extension.

The conceptual problem with your code is that you're mistakenly using an expandable (double-quoted) string ("...") to define your string template, which results in instant expansion (interpolation).

The point of using $ExecutionContext.InvokeCommand.ExpandString() is to pass it a string value with unexpanded variable references or subexpressions, in order to expand them on demand, with the then-current variable values and expression results.

To create such an unexpanded string value, you need a verbatim (single-quoted) string ('...').

Therefore, your code should be:

# Define the string template
# *as a verbatim string*, i.e. *single-quoted*
$o0='weird${tT}'

for ($i=1; $i -lt 3; $i++) {
  # (Re)define $tT
  $tT=$i
  # Use on-demand expansion of the value of $o0,
  # which uses the current value of $tT
  $ExecutionContext.InvokeCommand.ExpandString($o0)
}

Output:

weird1
weird2