Begin, process, and end

A script or function often begins with comment-based help, followed by a param block, and then one or more of the named blocks may be used.

In a script or function, if none of the blocks are declared, content is automatically placed in the end block.

In a filter, if none of the blocks are declared, content is automatically placed in the process block. This is the only difference between a function and a filter.

The named blocks refer to the processing of a pipeline and therefore make the most sense if the command is working on pipeline input.

This difference in default block is shown in the following pipeline example. The function must explicitly declare a process block to use the $_ variable. The filter can leverage the default block:

PS> function first { process { $_ } }    # end block by default
PS> filter second { $_ } # process block by default
PS> 1..2 | first # Outputs the value of $_ from explicit process
1

2
PS> 1..2 | second # Outputs the value of $_ from implicit process
1

2
Misuse of begin, process, and end

It is not uncommon to see begin, process, and end blocks used as regions, grouping the code required to set up, run, and tear down a function or script.

Care must be taken if converting such a function to accept pipeline input. It is often the case that all of the content must be moved to the process block to make sense of a function in a pipeline.

It is wise to plan to support an input pipeline for a command. However, using named blocks is optional. If a command is not expected to work on a pipeline, the content can be left to fall into the default block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.142.146