powershell - 格式化包含哈希表值的Powershell字符串

标签 powershell format hashtable

答案可能是微不足道的,但是我花了半个小时,仍然无法解决。

假设我有以下哈希表:

$hash = @{face='Off';}

我试图做的是将“face”的值与其他一些字符串元素一起输出。

这有效:
Write-Host Face $hash['face']
=> Face Off

但是,这不是:
Write-Host Face/$hash['face']
=> Face/System.Collections.Hashtable[face]

缺少空格以某种方式影响了运算符的优先级-它现在将$ hash评估为字符串,然后将其连接为[face]。

为了解决这个优先问题,我尝试了:
Write-Host Face/($hash['face'])
=> Face/ Off

现在,我有了多余的空间。
这行得通,但是我不希望多余的行重新分配:
$hashvalue = $hash['face']
write-host Face/$hashvalue
=> Face/Off

知道如何以单线方式工作吗?

最佳答案

当然,请使用子表达式:

Write-Host Face/$($hash['face'])

通常,如果我需要使用Write-Host精确控制空白,则只使用字符串:
Write-Host "Face/$($hash['face'])"

是的,在这种情况下,您再次需要一个子表达式,但更多,因为您根本不能在字符串中包含像$foo['bar']这样的表达式;否则)

顺便说一句,$hash.face的效果也很好,视觉困惑也更少。

关于powershell - 格式化包含哈希表值的Powershell字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540329/

相关文章:

asp.net - 如何确定生产 ASP.NET 站点是否正在以调试版本运行?

powershell - 如何手动解析 Powershell 命令行字符串

powershell - 如何使用 PowerShell 导入 CSV 文件?

powershell - 在 powershell 中对哈希表中的多个值进行排序

data-structures - 是否有一种插入时间为 O(1) 且还能保持排序顺序的数据结构?

powershell - 在PowerShell脚本中添加功能

c# - 字符串格式 : scale and precision from String. 格式

sqlite - 如何格式化 SQLite 的日期和时间值?

python - 基于变量类型的条件字符串表示

python - Python 中的哈希表