为什么 Clear-Variable 会降低内存使用量而重用变量却不会?

Why does Clear-Variable lower memory usage and reusing variables does not?

我有一个脚本可以从 vROps 获取虚拟机列表,并在 ForEach 循环中遍历它们。 我的 Azure Automation 沙箱在大约 15 分钟后内存不足,但如果我在 ForEach 循环的末尾放置一个 Clear-Variable,它会一直运行到 3 小时内存不足(叹息)...

在谷歌搜索无果后,我无法弄清楚为什么与仅覆盖相比,清除变量然后在下一次迭代中重新创建它需要 这么多 更少的内存它,它似乎慢慢地占用越来越多的内存。 所以,我的问题是,这是为什么?

继续我的评论。
在大多数情况下,您的 post 可能与此 SO Q&A

重复或非常接近

Powershell - "Clear-Item variable:" vs "Remove-Variable"

一些具体的争论点。

... 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.

因此,由于上述项目,历史上,我在启动时捕获默认会话内容...

$AutomaticVariables    = Get-Variable
$AutomaticVModules     = Get-Module
$AutomaticAliases      = Get-Alias
... and a few more

... 在我的代码中,在每个 运行 之后执行我的 Clear-ResourceEnvironment 函数,它确实...

  • 清除资源互操作
  • 在会话期间仅清除变量 created/used
  • 清除静态凭证存储,如果使用开关
  • 只清除会话期间加载的模块
  • 清除所有 PSSession
  • 强制启动 .Net 垃圾收集

...减轻这种影响。现在,当然,加载那么多也会对足迹产生影响。