1

The PowerShell script below runs continuously and generates output. This is a simplified version of a script which which I use to monitor processes running on my computer.

while ($true) { 
    get-date
    start-sleep 1
} 

I run this process in the the PowerShell ISE (Windows 10, PowerShell v5.1).

When this script runs, the memory used by the PowerShell ISE (powershell_ise.exe) increases continuously. Stopping the process stops the memory utilization increase.

Adding clear-host to the process does not help. The script below also uses an ever-increasing amount of RAM.

while ($true) { 
    clear-host  # <=== Added
    get-date
    start-sleep 1
} 

How can I limit the memory consumed by this continuously running process?

mherzog
  • 1,085
  • 1
  • 12
  • 24
  • 2
    how about: `[gc]::Collect()`? – Abraham Zinala Jan 03 '22 at 17:26
  • 3
    As an aside: The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run PowerShell (Core) 6+. The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](https://code.visualstudio.com/) with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell). – mklement0 Jan 03 '22 at 21:05
  • I would like to know why garbage collection is needed here. My loop isn't creating anything new. – mherzog Jan 03 '22 at 21:48
  • 1
    *"my loop isn't creating anything new"*, oh, but it is! Each loop creates a place in memory where the first iteration of `Get-Date` was stored, regardless if it was disposed of right after. This is why `[gc]::Collect()` "*frees*" that space in memory by manually calling in the garbage collection that only gets called under certain circumstances. – Abraham Zinala Jan 03 '22 at 22:28
  • @[Abraham Zinala], I'd love to learn more about this. How does a simple call to ``get-date``` take up increasing amounts of memory? There are no references to this object. – mherzog Jan 06 '22 at 01:40
  • I just deleted the following: @Abraham Zinala, ```[gc]::Collect()``` seems to work. Thank you! If you'd like to turn this into an answer, I'll accept it. – mherzog Jan 3 at 21:38. – mherzog Jan 10 '22 at 19:39
  • The reason I deleted my comment is that ```[bc]:Collect()``` helps but does not solve the issue. Even when not running PowerShell from using the ISE (using VS Code), memory utilization of my process continues to grow. – mherzog Jan 10 '22 at 19:40
  • 1
    Because memory is still being used. You can try assigning the cmdlets you're not using to `$null` and seeing if that helps: `$null = Clear-Host` and `$null = Start-Sleep 1` so it can be discarded at run time. – Abraham Zinala Jan 10 '22 at 20:02

0 Answers0