O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required