concept scriptblock in category powershell

appears as: scriptblocks, scriptblock, scriptblock, The scriptblock, A scriptblock, scriptblocks
Windows PowerShell in Action, Third Edition

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.

First, a preview of things to come. PowerShell has something called a scriptblock which is a fragment of code that you can pass around as an object itself. This is a powerful concept, and we’ll cover scriptblocks in great detail in later chapters, but for now we’re going to look at them in the context of parameter binding.

Here’s how scriptblock parameters work. Normally, when you pipe two cmdlets together, the second cmdlet receives values directly from the first. Scriptblock parameters (you could also call them computed parameters) allow you to insert a piece of script to perform a calculation or transformation in the middle of the pipelined operation. This calculation can do pretty much anything you want because a scriptblock can contain any element of PowerShell script.

What we call scriptblocks in PowerShell are called anonymous functions or sometimes lambda expressions in other languages. The term lambda comes from the lambda calculus developed by Alonzo Church and Stephen Cole Kleene in the 1930s. A number of languages, including Python and dialects of LISP, still use lambda as a language keyword. In designing the PowerShell language, the PowerShell team felt that calling a spade a spade (and a scriptblock a scriptblock) was more straightforward (the coolness of using Greek letters aside).

We’ve said that scriptblocks are anonymous functions, and functions are one of the types of commands in PowerShell. But wait! You invoke a command by specifying its name. If scriptblocks are anonymous, they have no names—so how can you invoke them? This necessitates one more diversion before we dig into scriptblocks. Let’s talk about how commands can be executed.

What you’ve been writing to create scriptblocks is called a scriptblock literal—a chunk of legitimate PowerShell script surrounded by braces. The syntax for this literal is shown in figure 10.1.

Figure 10.1. Defining a simple scriptblock. Note that the param statement is optional, so a minimal scriptblock has only the braces.

The definition of a scriptblock looks more or less like the definition of a function, except the function keyword and function name are missing. If the param statement isn’t present, the scriptblock will get its arguments through $args, exactly as a function would.

Now execute the scriptblock using the & call operator:

PS>  & $sb
2
4
6
8

The scriptblock executes, printing out the even numbers from 2 to 8.