PowerShell中哈希表值的字符串插值

时间:2012-05-25 12:38:08

标签: powershell

我有一个哈希表:

$hash = @{ First = 'Al'; Last = 'Bundy' }

我知道我可以这样做:

Write-Host "Computer name is ${env:COMPUTERNAME}"

所以我希望这样做:

Write-Host "Hello, ${hash.First} ${hash.Last}."

...但我明白了:

Hello,  .

如何在字符串插值中引用哈希表成员?

4 个答案:

答案 0 :(得分:53)

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

答案 1 :(得分:14)

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

答案 2 :(得分:3)

如果你愿意的话,增加一个小功能,可以更通用一些。但请注意,您正在$template字符串中执行可能不受信任的代码。

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)

答案 3 :(得分:0)

无法让Lemur's answer在Powershell 4.0中工作,如下所示

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)
}