PowerShell - Filter Versus Function

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

A filter is a ‘simplified’ function type that automatically uses the Process block (no Begin and End blocks) and therefore executes on every object.

A filter natively manages pipeline objects and performs a loop on each object.

# Explicit Process block
Function Test-Function {
process { $_ }
}
# Implicit Process block
Filter Test-Filter { $_ }
# Behaviour check
1..3 | Test-Function
1..3 | Test-Filter

Filter is interesting for doing simple checks and actions on each object in the pipeline, for the rest use a function instead.

# Create a folder if it doesn't exist with Filter
Filter New-Folder
{
if (!(Test-Path -Path $_ -PathType Container)) {
New-Item -Path $_ -ItemType Directory
}
}
c:\test','c:\test2' | New-Folder
# Create a folder if it doesn't exist with a function
Function New-Folder {
process {
if (!(Test-Path -Path $_ -PathType Container)) {
New-Item -Path $_ -ItemType Directory
}
}
}
'c:\test3','c:\test4' | New-Folder

Related links