Search code examples
powershellvariablesscopegarbage-collection

Powershell Remove-Variable cmdlet, do I need to call it at the end of each function/scriptblock?


This is a generic question, no code. Not sure if I need to remove local variables as I thought it should be done by the Powershell Engine. I had a script to gather info from WMI and used a lot of local variables. The output was messed up when running multiple times, but it got fixed after I clean up all local variables at the end of function/scriptblock.

Any thoughts/idea would be appreciated.


Solution

  • The trouble do not come from the fact that you do not remove your vars, but by at least from two beginers errors (or done by lazy developpers like me, supposing I'am a developper).

    1. we forget to itialize our vars before using them.
    2. we do not test every returns of our functions or CmdLets calls.

    Once these two things done (code multipled by two at least) you can restart your script without cleaning anything except the processed datas.

    For me scripting is most of the time done on a corner of a table even not push in a source repository.

    So start scripting and ask yourself fewer questions.