The filter Keyword in PowerShell

Rohan Timalsina Apr 04, 2022
The filter Keyword in PowerShell

A function is a collection of PowerShell statements that has a name assigned. To run the function, you have to type the function name.

The statements in a function run after you run the function. A function must be defined before it can be called.

A filter is a special type of function that uses the filter keyword. This tutorial will teach you to use the filter function in PowerShell.

Use the filter Function in PowerShell

The filter is a function that runs on each object in the pipeline. All its statements are included within a process block in the filter function.

Normally, a function uses the Begin or the End parameter, but a filter function only has the process block.

Syntax:

filter [<scope:>]<name> { <statement list> }

The main purpose of a filter function is to process input from the pipeline. It helps process pipeline input faster and more efficiently.

The following example takes 1,2,3 as input from the pipeline and displays the whole input.

Command:

filter Input {
    $_
}
1, 2, 3, 4, 5 | Input

The automatic variable $_ helps capture the pipeline’s input object.

Output:

1
2
3
4
5

It is not required to use the ForEach loop in the filter function because the loop functionality is already built-in.

Command:

filter Input {
    if ($_ -eq 2) {
        $_
    }
}
1, 2, 3, 4, 5 | Input

Output:

2

The following filter function gets files object from the pipeline and then displays them in the output.

Command:

filter Get-Files {
    $_
}
Get-ChildItem C:\folder2 -Recurse -ErrorAction SilentlyContinue | Get-Files

In the above script, the Get-Child cmdlet recursively gets items in the directory C:\folder2.

Output:

Directory: C:\folder2

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         2/23/2022  11:39 PM                New folder
-a----         2/23/2022  10:29 PM              0 books.txt
-a----         2/23/2022  10:29 PM              0 hello.txt

Directory: C:\folder2\New folder

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         2/23/2022  10:26 PM              0 cars.txt

We hope this article helps you understand how to use the filter function in PowerShell. For more information, read Working with Functions in Windows PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website