4.1. Defining Script Blocks

Defining a script block literal is as simple as surrounding several program statements with curly braces. The statements will not be executed immediately; instead, a new script block object will be created and returned. Here is our first script block:

PS> { Write-Host "Hello from a script block" }
Write-Host "Hello from a script block"

As you can see, the actual Write-Host statement did not execute. We got back a script block object whose string representation is the script code contained inside the block. There is little value in creating blocks if we do not keep references to them so that we can use them later. Here is how to assign a newly created block to a variable:

PS> $helloBlock = { Write-Host "Hello from ...

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.