PowerShell Filters and Functions
The other day I saw social media post from Adam Bertram about PowerShell filters. Talk about a blast from the past. Back in the early days of PowerShell, when scripting was still in its infancy, we could write functions
or filters
. Filters were a special type of function that was optimized for processing data in the pipeline. They were a way to make your scripts more efficient by reducing the amount of memory used and the number of objects created. I think they have fallen out of favor as most people simply write functions. But Adam raised the issue of performance, so I thought we'd spend a little time comparing filters and functions and figure out if there is a place for filters in today's PowerShell.
Your first thought might be, "I can already filter with Where-Object. What's the big deal." In many situations you may be right.
PS C:\> dir c:\scripts\ -file | where {$_.LastWriteTime -gt (Get-Date).AddHours(-36)}
Directory: C:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 5/22/2024 3:31 PM 1214 select-until.ps1
But what if you run this command often? Or would like to customize it. Suppose I want files modified in the last 48 hours? A filtering function might be a better choice.