Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy a dictionary (hashtable) in PowerShell

Tags:

powershell

Clone() only does a shallow copy and it seems there is no straightforward way to do this in C# without a bit of boilerplate code wrapping serialization (How do you do a deep copy of an object in .NET (C# specifically)?). Is there a simple way to do this in Powershell without referencing external libraries ?

like image 980
WaffleSouffle Avatar asked Sep 19 '11 09:09

WaffleSouffle


People also ask

How do I copy a Hashtable in PowerShell?

Copying Hashtables (For Real) For a one-level hashtable like the above example, use the . Clone() method. This method creates a new hashtable object and assigns it to a variable. Let's create $person3 by cloning $person1 , then follow this up by adding a new property to $person3 .

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'

What is GetEnumerator in PowerShell?

GetEnumerator in PowerShell is used to iterate through the Hashtable or array to read data in the collection. GetEnumerator doesn't modify the collection data. Use foreach or foreach-object in PowerShell to iterate over the data read from the GetEnumerator.

Does PowerShell have dictionary?

Creating Ordered DictionariesYou can create an ordered dictionary by adding an object of the OrderedDictionary type, but the easiest way to create an ordered dictionary is use the [ordered] attribute. The [ordered] attribute is introduced in PowerShell 3.0. Place the attribute immediately before the "@" symbol.


1 Answers

All the libraries you need are there when you start the shell so it's just to implement the deep copy as per your link.

function Clone-Object {
    param($DeepCopyObject)
    $memStream = new-object IO.MemoryStream
    $formatter = new-object Runtime.Serialization.Formatters.Binary.BinaryFormatter
    $formatter.Serialize($memStream,$DeepCopyObject)
    $memStream.Position=0
    $formatter.Deserialize($memStream)
}
like image 84
CosmosKey Avatar answered Sep 21 '22 23:09

CosmosKey