【发布时间】:2020-10-26 12:02:20
【问题描述】:
我的ConvertTo-Expression 项目收到了这个Remove quotes in HashTables Keys when possible 请求。
关键是我并不完全清楚何时应该在哈希表中实际引用键。
与参数值一样,不带引号的哈希表键的使用仅限于某些字符。
不允许使用多个字符(包括空格),例如:
$Options = @{
Margin = 2
Padding = 2
Font-Size = 24
}
会导致错误:
Line | 4 | Font-Size = 24 | ~ | Missing '=' operator after key in hash literal.
在某些情况下,仅字符的顺序可能会导致错误甚至陷阱,例如:
$Hashtable = @{
U2 = 'YouTo'
2U = 'ToYou'
}
$Hashtable.keys
2
U2
(这是因为U2 键将被解释为[UInt32] 类型,这意味着$HashTable.2U 将正确显示该值,但$HashTable.2、$HashTable.'2' 和$HashTable.'2U' 不会。)
除了我正在寻找一些记录在案的最佳实践的问题之外,我想安全地测试一个字符串是否需要被引用,例如:
IsStringConstant 'Margin' # True
IsStringConstant 'Font-Size' # False
IsStringConstant 'U2' # True
IsStringConstant '2U' # False
我一直在玩AST,但这需要我先构建一个ScriptBlock,即considered unsafe。
有没有办法检查字符串是否需要为哈希表键引用?
【问题讨论】:
标签: powershell