Powershell 3.0提供了一种快速创建哈希表的方法,可以维持其顺序,但代价是内存支出略有增加。
问题:
# create ordered hashtable
$a = [ordered]@{}
# populate with 3 key-value pairs
$a['a'] = 15
$a['b'] = 10
$a['c'] = 9
$a
# Name Value
# ---- -----
# a 15
# b 10
# c 9
# get value for key = 'b'
$a['b']
# returns: 10
# get value for indexed last (ordered) item in table: This is desired behaviour
$a[-1]
# returns: 9
# show type of object for variable $a
$a | Get-Member
# returns: TypeName: System.Collections.Specialized.OrderedDictionary
# ...
到目前为止一切都很顺利。
将对象序列化为磁盘,然后反序列化时,对象从System.Collections.Specialized.OrderedDictionary更改为反序列化 .System.Collections.Specialized.OrderedDictionary。
# serialize to disk
$a | Export-CliXml ./serialized.xml
# deserialize from disk
$d = Import-CliXml ./serialized.xml
# show datatype of deserialized object
# returns: Deserialized.System.Collections.Specialized.OrderedDictionary
# ...
# $d variable is still indexed by key, but not by integer index
$d['b']
# returns: 10
# request the first item in the dictionary by numerical index
$d[0]
# returns: nothing/null, this is undesired behaviour. AARGH!
当然,我认为反序列化的有序词典应该像Ordered Dictionary在保存到磁盘之前那样运行,特别是能够通过数字索引和键检索哈希表项。
由于Powershell目前不是这种情况,有没有一种快速方法可以将反序列化对象转换为对象的基本版本,而无需对整个反序列化对象进行操作?
答案 0 :(得分:0)
要序列化/反序列化并保留[Ordered]
对象的顺序,您可以考虑使用ConvertTo-Expression cmdlet(请参阅:'Save hash table in PowerShell object notation (PSON)'问题):
$Expression = ConvertTo-Expression $a
$b = &$Expression
$b
Name Value
---- -----
a 15
b 10
c 9