Search code examples
powershellmemorymemory-leaksdispose

Disposal and cleanup in PowerShell - manual or automatic?


I have been working in PowerShell fairly heavily in these past several months. Gotta say, it took me by surprise. What I thought was just an over-inflated version of CMD is actually a very robust, object-oriented, and versatile .NET language.

My previous experience in languages (all self-taught) have been Java, C++, and Wiring (watered-down Arduino/Particle variant of C++) where a great deal was in constrained environments (CoAP). Working in constrained, embedded environments made me more cognizant of memory handling and appropriation*. If your system resources are limited, memory leaks can be devastating when left unchecked.

With that being said, I'm not sure if PowerShell intuitively handles memory allocations and disposal. Because it is a higher-level language, it makes sense that those are taken care of behind the scenes but I want to make sure. I saw a PowerShell script that actually called $object.Dispose() when it was done with that particular $object.

So, do I need to call a Dispose() method for each New-Object that I create?

Thanks!


*I understand that there is a drastic difference in a system like an ATMega328P microcontroller (30kb ROM\2kb RAM) compared to an information system like a computer or server, however, if left in a persistent run-state, memory leaks add up and could very possible result in a crash. Also, I am aware that everything is dumped once the session has ended.


Solution

  • It's not required, but it's still good practice. Without it PowerShell will still clean up after you, but it might take considerably longer. Of course objects won't be automagically disposed as long as your code holds a reference to them.

    Related.