5.2. Filters

As you already know, most PowerShell scripting is about pipelines. The way to accept pipeline input in a function is to define begin, process, and end sections inside the function. Those sections are executed when the function has something piped to it. Of the three sections, process is the only mandatory one—it is executed for each object that has been piped in. As usual, inside the process section, we can refer to the current object using the $_ special variable. The begin and end sections are executed before and after the pipeline has been processed. Since an example is worth a thousand words, here is a function that accepts a pipeline of files and calculates their total size:

PS> function Get-Size { begin { $total = 0 } process ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.