Beyond Impact Blog

Garbage Collection in Powershell to Speed Scripts

Apr 25, 2018 12:50:46 PM / by Cole McDonald

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:


I wish I'd recalled that I'd used this before running the script I'm staring at now.  It'll definitely be added before I have to run it again.


Did you find this article useful?  Let me know at

If you want to be kept informed, follow our RSS feed:

Learn more about Azure PowerShell.

Beyond Impact is a Cloud Hosting and Managed Services provider based in Minneapolis, Minnesota.
You can learn more about our Cloud Services at

Tags: powershell, automation, loops, devops

Cole McDonald

Written by Cole McDonald

Internet Pioneer, Digital Futurist

Subscribe to Email Updates

Recent Posts