As we saw earlier, it's easy to start with several simple tasks and join them together to create increasingly complex scripts and pipelines. At some point, instead of using the recall buffer, it is convenient to store command sequences in scripts for later reuse. Functions serve a similar purpose by enabling us to collect one or more commands and group them together so that they may be run with a single command. What sets functions apart is that they can be used to return a result based on the processing of a set of inputs—in effect, the function becomes a black box that encapsulates some frequently used logic.
Several of the built-in commands, such as
clear-host, are, in fact, functions that perform tests, determine parameters, and invoke cmdlets based on their inputs. The
new-item cmdlet is very flexible, yet at the same time, it can have a cumbersome syntax; thus, MSH creates these short-cut functions for convenience. Even familiar commands such as
D: are functions that call the
We'll see how functions offer the means to bring together the various topics we've seen in this chapter, including variables, conditional tests, and loops. Functions can range from the very simple to the surprisingly complex, yet they invariably offer a way to arrange scripts neatly in logical sections, making them much easier to understand and maintain than other methods.
For our first function, let's start with something ...