String interpolation of hashtable values in PowerShell
I've got a hashtable:
$hash = @{ First = 'Al'; Last = 'Bundy' }
I know that I can do this:
Write-Host "Computer name is ${env:COMPUTERNAME}"
So I was hoping to do this:
Write-Host "Hello, ${hash.First} ${hash.Last}."
...but I get this:
Hello, .
How do I reference hash table members in string interpolation?
Write-Host "Hello, $($hash.First) $($hash.Last)."
"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]
With the addition of a small function, you can be a bit more generic, if you wish. Watch out, though, you're executing potentially untrusted code in the $template
string.
Function Format-String ($template)
{
# Set all unbound variables (@args) in the local context
while (($key, $val, $args) = $args) { Set-Variable $key $val }
$ExecutionContext.InvokeCommand.ExpandString($template)
}
# Make sure to use single-quotes to avoid expansion before the call.
Write-Host (Format-String 'Hello, $First $Last' @hash)
# You have to escape embedded quotes, too, at least in PoSh v2
Write-Host (Format-String 'Hello, `"$First`" $Last' @hash)