PowerShell中哈希表值的字符串插值
我有一个哈希表:PowerShell中哈希表值的字符串插值,powershell,Powershell,我有一个哈希表: $hash = @{ First = 'Al'; Last = 'Bundy' } 我知道我可以做到这一点: Write-Host "Computer name is ${env:COMPUTERNAME}" 所以我希望这样做: Write-Host "Hello, ${hash.First} ${hash.Last}." …但我明白了: Hello, . 如何在字符串插值中引用哈希表成员?如果愿意,通过添加一个小函数,您可以更通用一些。不过,请注意,您正在执行$te
$hash = @{ First = 'Al'; Last = 'Bundy' }
我知道我可以做到这一点:
Write-Host "Computer name is ${env:COMPUTERNAME}"
所以我希望这样做:
Write-Host "Hello, ${hash.First} ${hash.Last}."
…但我明白了:
Hello, .
如何在字符串插值中引用哈希表成员?如果愿意,通过添加一个小函数,您可以更通用一些。不过,请注意,您正在执行
$template
字符串中可能不受信任的代码
Write-Host "Hello, $($hash.First) $($hash.Last)."
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)
}
这需要额外的括号:Write Host(“Hello{0}{1}.-f…”这些额外的
$
符号非常难看。我希望有更好的东西。@RogerLipscombe这是Powershell,它不是一种漂亮的语言,字符串插值特别讨厌!
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)
}