Exploring scriptblocks
A scriptblock is a collection of statements inside braces ({}
) that can be used as a single unit. We’ve already used them numerous times: in Where-Object
cmdlets, if
and else
statements, foreach
loops, and earlier in this chapter, when we were writing functions. In this section, we are going to look at some of the properties of scriptblocks and how we can use them in our code.
Consider everything we’ve just done on functions. A function consists of the function
keyword, a name, and a scriptblock: a set of statements inside braces. We don’t need the keyword to use the scriptblock – the keyword supplies a label that we use to call the scriptblock when we need it.
Scriptblocks return the output of all the statements they contain; this may be a single object or an array of objects. We can use the return
keyword, and it works the same as it does for a function: it will exit the scriptblock at that point.
We can create parameters...