This question is related to:
Unquoted tokens in argument mode involving variable references and subexpressions: why are they sometimes split into multiple arguments?.
I got this Remove quotes in HashTables Keys when possible request for my ConvertTo-Expression
project.
The point is that it is not fully clear to me when keys should actually be quoted in hash tables.
As with argument values, the use of unquoted hash table keys is limited to certain characters.
Several characters (including spaces) are not allowed, e.g.:
$Options = @{
Margin = 2
Padding = 2
Font-Size = 24
}
Will cause an error:
Line | 4 | Font-Size = 24 | ~ | Missing '=' operator after key in hash literal.
In some cases, just the order of the characters could lead to errors or even pitfalls, e.g.:
$Hashtable = @{
U2 = 'YouTo'
2U = 'ToYou'
}
$Hashtable.keys
2
U2
(This is because the U2
key will interpreted as a [UInt32]
type, meaning that $HashTable.2U
will correctly reveal the value but $HashTable.2
, $HashTable.'2'
and $HashTable.'2U'
not.)
Apart from the question that I am looking for some documented best practices for this, I would like to safely test whether a string needs to be quoted or not, something like:
IsStringConstant 'Margin' # True
IsStringConstant 'Font-Size' # False
IsStringConstant 'U2' # True
IsStringConstant '2U' # False
I have been playing with AST, but that requires me to build a ScriptBlock
first, which is considered unsafe.
Is there a way to check whether string requires to be quoted for a hash table key?