Garbage Collection in Powershell to Speed Scripts
I've recently produced a couple of scripts that produce large, in memory objects that they're storing out to a CSV file as they go. My thread counts for Powershell are running high as I'm looping through several instances of these larger objects. Although my CPU and Memory are fine per the Resource Manager, the script is running very slowly and the thread count continues to rise.
One more recent of these is a script to handle aging and retention of SQL backups in Azure Blob Storage. There are millions of files I'm processing. To handle the memory and thread creep, I found you can use the system's builtin garbage collection method to reign in these objects. I just add the following to the top of my foreach loop: