In this post we will be going over filtering in PowerShell and different methods available.
Filtering should be done as close to the source command as possible, this will speed up the time it takes for the command to complete and return the data.
Depending on the command used there can be a filter parameters available, if there is no filtering we would use where-object.
Where-Object can be used to filter objects based on any property that is returned from the command.
If we need help with example or the right syntax to run the command we can use
Get-Help Where-Object
Get-Help Where-Object -Examples

Where-object can be used with lots of filtering parameters to return objects like Contains, eg (equal to), gt (greater than), lt (less than), like…….
Once we have the syntax worked out we can start to filter the data to returned. In the below command we will return any file that has .pdf extension and just select the name to make the results easier to read.
Get-ChildItem -Path 'C:\Program Files\' -Recurse -File | Where-Object {$_.Name -like "*.pdf"} | Select-Object Name

Get-ChildItem has a filter parameter, this allow us to test and show the speed difference when we can.
Below is the time when running the command using where-object.

When we use the -filter with Get-ChildItem we can see that the time to run went from 6 second to 2 seconds.

This was only a small subset of data but if we where running against thousand or hundred of thousand of files this can add up and save minutes to hours of time for data to returned.