11

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 ?

Community
  • 1
  • 1
WaffleSouffle
  • 3,293
  • 2
  • 28
  • 27
  • what's the high level requirement here? are you aware of the subtleties of a "deep" copy when member fields (or in this case, values) are reference types? (ignoring serialization effects) – x0n Sep 19 '11 at 14:43
  • 1
    That approach using serialisation relies on all the objects (and member objects recursively) being serialisable – which is not always true. .NET, and therefore anything built on it that doesn't implement it itself, has no generic deep copy (and, in general, it isn't possible without the coöperation of all types). However specific approaches can work in specific cases, but more context would be needed to be able to identify possibilities. – Richard Sep 19 '11 at 09:37
  • This started out as a requirement to copy the nested dictionary returned from [Parsing an ini file](http://stackoverflow.com/questions/417798/ini-file-parsing-in-powershell/6680290#6680290), and then I got curious about something more generic. Plus I originally used Clone() without remembering it didn't deep copy. – WaffleSouffle Sep 20 '11 at 13:18

1 Answers1

17

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)
}
CosmosKey
  • 1,287
  • 11
  • 13
  • I knocked up a poor-man's recursive copy because I was mainly dealing with built-in types, and expected calling into the libraries from powershell to be hard work. Thanks for showing it's actually straightforward. – WaffleSouffle Sep 20 '11 at 13:14
  • 4
    For completeness' sake, I'll mention that "Clone" is not an [Approved Verb](https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx). The verb "Copy" should be used instead. – bshacklett Jun 22 '15 at 17:51