Question:
I’m trying to template some strings using Powershell string expansion. When I use a string literal it’s fine, but when I pass the string as a variable it doesn’t work. What do I need to do differently?
1 2 3 4 5 6 7 8 9 |
$list = Get-Process # this works fine $list | ForEach-Object {"$($_.ProcessName)"} # this doesn't $template = "$($_.ProcessName)" $list | ForEach-Object {$template} |
Answer:
You cannot do this with just a normal string. However, you could put the string inside a scriptblock and then invoke it with the call operator &
:
1 2 3 |
$template = {"$($_.ProcessName)"} $list | ForEach-Object {&$template} |