5

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'.

Akaizoku
  • 456
  • 5
  • 19

3 Answers3

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 }
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
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()
Theo
  • 57,719
  • 8
  • 24
  • 41
1

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()