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 ?
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 .
@{} 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'
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With