PowerShell Copy, Shallow and Deep

Back in March, when I started this post, I was reading over some Python code. Yeah,… you read that right. As I did that, I was introduced to a term I don’t think I’ve seen before: It was “deepcopy.” The Python module import looked like this: from copy import deepcopy. Deepcopy, what is that?

I don’t remember the name for it, but as I read up on this term and the function from this Python module, I do remember coming up against this in PowerShell. Essentially, it’s this. If you make a copy of an array—we’ll use that for this example—changes to the original array will change the copy, as well. The deepcopy option allows Python to create a copy that isn’t tied to the original. Let’s begin by looking at a shallow copy example in PowerShell.

Any change made to the original object—$Array—will be seen in the copy of the object, too. There’s a link between them. As a shallow copy, its values will continue to reference the original object. A deep copy is independent; there is no reference to the original object. Let’s work through a quick example of making a deep copy of our array in PowerShell.

I gather that there may be other ways to create deep copies, and you’re welcome to comment and share those if you’d like. This is an extremely simple and straightforward example—my favorite—of something of which you may need to be careful, as you continue to write PowerShell.

One thought on “PowerShell Copy, Shallow and Deep

  1. David Berg

    Actually, you’re still making a shallow copy, just one level higher up. Originally, you made a shallow copy of the array pointer, now you’re making a shallow copy of the array itself; however, if anything in the array is an object, your second array still refers to the same object. To truly make a deep copy, you need to repeat the copy iteratively all the way down the properties (which is cumbersome, and most people won’t do it). I have done this myself, but only for certain types of objects (hash tables and arrays). Fortunately, it’s often not necessary (but sometimes it is).

    Here’s an article on how it works in Python: https://www.educba.com/python-deepcopy/

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *