Powershell Clone Ordered Hashtable
Asked Answered
E

3

6

Follow-up from this thread.

Issue

An ordered hashtable cannot be cloned.

Question

Is there an "easy" way to do this? I have indeed found some examples that seem overly complicated for such a "simple" task.

MWE

$a = [ordered]@{}
$b = $a.Clone()

Output

Method invocation failed because [System.Collections.Specialized.OrderedDictionary] does not contain a method named 'Clone'.

Eighteenth answered 31/8, 2018 at 13:32 Comment(1)
Related: Deep copy a dictionary (hashtable) in PowerShellMonogamy
B
8

OrderedDictionary do not contain Clone method (see also ICloneable interface). You have to do it manually:

$ordered = [ordered]@{a=1;b=2;c=3;d=4}
$ordered2 = [ordered]@{}
foreach ($pair in $ordered.GetEnumerator()) { $ordered2[$pair.Key] = $pair.Value }
Butylene answered 31/8, 2018 at 14:0 Comment(0)
V
4

While the answer given by Paweł Dyl does clone the ordered hash, it is not a Deep-Clone.

In order to do that, you need to do this:

# create a deep-clone of an object
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $ordered)
$ms.Position = 0
$clone = $bf.Deserialize($ms)
$ms.Close()
Volt answered 1/9, 2018 at 8:58 Comment(2)
BinaryFormatter is obsoleted. Do you have a modern method?Yulma
@Yulma I haven't tried it yet, but MessagePack looks promisingVolt
S
2

If you're willing to lose the ordered aspect of it, a quick solution could be to convert to a normal hashtable and use its Clone() method.

$b=([hashtable]$a).Clone()
Signatory answered 6/10, 2020 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.