PowerShell foreach file in folder using a lot of memory


I’m fairly new to PowerShell and programming, so I’m sure this code can be optimized even more.

However, my biggest problem with this code is that it puts it’s data from the foreach loop in memory. What is the best way to prevent this?

I started up rewriting this script from a script that I found here: PowerShell: delete files older than x days

Edit: Oh, there is about 60 000~ files in each TargetFolder by the way.

This version works. Thanks to all who helped!



Much more performant than using include (on a large set of files). Or even better:


I see now, your problems are due to include! If you need to use wildcards and nor regular expressions to get the child item, use filter instead. Is much more performant because does not use regular expression matching.


even if it’s not very clear what you are filtering there (or you want include)…everything? May be you don’t need the wildcard at all.

In my humble opinion, the best way to prevent foreach loop in memory is piping. However, due to the nature of your script (many nested controls inside the loop) it’s not that easy.

Try with:

even if I doubt it will improve performances.



PowerShell foreach file in folder using a lot of memory by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply