Best Practice - Array Removing

Fellow Powershellers.
I am still coming up to speed on powershell. My question is about arrays.
1 - If you create an array at the top of your script, it is really necessary to Clear it or Remove it at the end of your script?. years ago, I believe I was told to Clear them.

MG

Mark,

I’d say that depends pretty much on your circumstances. If you create arrays in scripts they’re gone anyway when the scripts ends. They only live in the script scope. :wink:

If you have a PowerShell session with a REALLY giant array blocking a lot of memory and you’re about to continue using this session you created that enormous array in you may remove it to free the memory it took. But technically - apart from some paranoic security concerns about reading your memory and spying on you - there’s no reason I’m aware of that makes it necessary to remove arrays you don’t need anymore.

HI Olaf, Many thanks.
so, lets say your are not running a script as such. You are using the Powershell UI and just typeing your code in the script window. When you finsih running your powershell commands, do the arrays get destroyed automatically or are they still hanging aournd. The code in this scenario/window would be rebuilding them again in that they are at the top.

thx Mark

As long as PowerShell console session lives the arrays remain in the memory. They will not get destroyed automatically.

I didn’t get that. Sorry.

Hi Olaf,
Ok. Almost there.
So, lets say I am running interactively in the powershell ui. At the begginging of the powershell comands, I declare the arrays. Since that session is always being used, interactivly, should I be CLEARING out the array at the end of the run?
thx

Mark

I actually already answered that. :wink:
If your OCD does not command you so and those arrays are not GB big there is no technical reason I’m aware of that tells you to remove or clear them. Think of them like bascets of things in a big room. If you don’t need them they just are there doing nothing than taking a little space from the room. If you need the space for something else you can move them out. Otherwise just ignore them.

AND … if you want to get rid of them the fastest way would be to restart your PowerShell console session instead of removing or clearing a bunch of single arrays. :+1:t4:

HI Olaf,

OK. Thanks. The reason I reasked the question was that I was thinking there was a difference in how the array, and its caching/cleanup, was handled when running interactively as compared to a script.

Thanks for the info. You have answered all my questions.

MG

… well, actually there is … I thought I’ve made that clear. And it’s not just about arrays - it’s about actually everything.

You may generalize the concecpt by reading the help

HI Olaf, Thanks. Mark