45

我有一个哈希表:

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

我知道我可以这样做:

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

所以我希望这样做:

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

...但我明白了:

Hello,  .

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

4

4 回答 4

86
Write-Host "Hello, $($hash.First) $($hash.Last)."
于 2012-05-25T12:42:16.340 回答
22
"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]    
于 2012-05-25T12:45:29.717 回答
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)
于 2013-06-10T21:37:01.737 回答
0

无法让狐猴的答案在 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)
}
于 2015-02-19T14:10:54.233 回答