我有一个哈希表:
$hash = @{ First = 'Al'; Last = 'Bundy' }
我知道我可以这样做:
Write-Host "Computer name is ${env:COMPUTERNAME}"
所以我希望这样做:
Write-Host "Hello, ${hash.First} ${hash.Last}."
...但我明白了:
Hello, .
如何在字符串插值中引用哈希表成员?
我有一个哈希表:
$hash = @{ First = 'Al'; Last = 'Bundy' }
我知道我可以这样做:
Write-Host "Computer name is ${env:COMPUTERNAME}"
所以我希望这样做:
Write-Host "Hello, ${hash.First} ${hash.Last}."
...但我明白了:
Hello, .
如何在字符串插值中引用哈希表成员?
Write-Host "Hello, $($hash.First) $($hash.Last)."
"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]
通过添加一个小功能,如果您愿意,您可以更通用一点。但请注意,您正在执行$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)
无法让狐猴的答案在 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)
}