我有一个哈希表:
$hash = @{ First = 'Al'; Last = 'Bundy' }
我知道我可以做到:
Write-Host "Computer name is ${env:COMPUTERNAME}"
所以我希望这样做:
Write-Host "Hello, ${hash.First} ${hash.Last}."
...but我得到了这个:
Hello, .
如何在字符串插值中引用哈希表成员?
发布于 2012-05-25 20:42:16
Write-Host "Hello, $($hash.First) $($hash.Last)."
发布于 2012-05-25 20:45:30
"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]
发布于 2013-06-11 05:37:02
通过添加一个小函数,您可以更通用一些,如果您愿意的话。但是要小心,您正在$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)
https://stackoverflow.com/questions/10754582
复制相似问题