Roger Lipscombe
Roger Lipscombe

Reputation: 91825

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?

Upvotes: 49

Views: 26061

Answers (4)

WaffleSouffle
WaffleSouffle

Reputation: 3363

Couldn't get Lemur's answer to work in Powershell 4.0 so adapted as follows

Function Format-String ($template) 
{
  # Set all unbound variables (@args) in the local context
  while ($args)
  {
    ($key, $val, $args) = $args
    Set-Variable -Name $key.SubString(1,$key.Length-2) -Value $val
  }
  $ExecutionContext.InvokeCommand.ExpandString($template)
}

Upvotes: 0

Lemur
Lemur

Reputation: 462

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)

Upvotes: 3

Angshuman Agarwal
Angshuman Agarwal

Reputation: 4866

"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]    

Upvotes: 24

David Brabant
David Brabant

Reputation: 43499

Write-Host "Hello, $($hash.First) $($hash.Last)."

Upvotes: 94

Related Questions