Continuing from my comment.
For the most part, your post could be a duplicate or very close to this SO Q&A
Powershell - "Clear-Item variable:" vs "Remove-Variable"
Some specific points of debate.
... reference is the last reference to the object then the GC will determine when the memory for said object is collected. However, if you no longer need the variable then use Remove-Variable to also allow the memory associated with the System.Management.Automation.PSVariable object to be eventually collected as well.
... Remember, Powershell is all .NET, with its famous memory management. Always control your scope and make sure variables get out of scope as soon as they are not needed. For example, if temporary variables are needed inside loops, they will invalidate at loop's end automatically
... To clear variable data/content is to remove all variables running in the current session using:
Remove-Variable -Name * -ErrorAction SilentlyContinue This removes all variables immediately. In fact, I add this to the end of some of my scripts, so that I can be sure that running another script with potentially the same name, will not have new data added and cause undesired results.
Thus, because of items like the above, historically, I capture default session stuff on startup...
$AutomaticVariables = Get-Variable
$AutomaticVModules = Get-Module
$AutomaticAliases = Get-Alias
... and a few more
... and in my code execute my Clear-ResourceEnvironment
function after each run, which does...
- Clear resource interop
- Clear only variables created/used during the session
- Clear static credential store, if the switch is used
- Clear only modules loaded during the session
- Clear all PSSessions
- Force start .Net garbage collection
... to alleviate such impacts. Now, of course, loading that much also has footprint impacts.