PowerShell Scriptblocks

A ScriptBlock is a collection of statements surrounded with { curly parenthesis }
a scriptblock can be saved in a variable and executed using the & call operator


$alert = { "Hello World" }
& $alert
& $alert

Notice that to execute a ScriptBlock you must use the call operator&”, just defining the ScriptBlock is not enough.

Multiple lines

A script block can be written to include multiple lines of code:

PS C:\> $mysb = {$a = 123
Echo $a
PS C:\> & $mysb

However in many of the places where you will want to use a scriptblock, it is more convenient to keep everything on a single line, so use the ';' continuation character:

PS C:\> $mysb = {$b = 456 ; Echo $b }
PS C:\> & $mysb

For very long blocks of code, you should use either a function or a script rather then cramming too much into a single line.


Just like a function, we can add a param block to make the scriptblock more flexible:

$alert = { param ($message) "$message" }
& $alert -Message "Hello World"

When passing a variable to a scriptblock it is important to consider the variable scope.

  1. Each time the scriptblock is run; it will dynamically read the current value of the variable.
  2. When a scriptblock is run using the “&” (call) operator, updates to a variable are not reflected in the parent scope.
  3. When a scriptblock is run using the “.” (dot) operator, updates to a variable apply to the current scope.


GetNewClosure can be used to reverse the above behaviour (1.) so that a variable will only be read when the scriptblock is initialised. This makes the scriptblock self-contained or closed:

PS C:\> $name = "Hello world"
PS C:\> $ScriptBlock = {$name}
PS C:\> $closedScriptBlock = $ScriptBlock.GetNewClosure()

PS C:\> & $scriptblock
Hello world
PS C:\> & $closedScriptBlock
Hello world

Now if we change the variable and re-run the scriptblock, the closed version does not pick up the change:

PS C:\> $name = "New Green shoes"
PS C:\> & $scriptblock
New Green shoes
PS C:\> & $closedScriptBlock
Hello world

Begin {}, Process {} and End {} blocks can be added to a scriptblock, just like a function

For anything more complex, you can take the scriptblock one step further and turn it into a Function or Filter.

“I…confess to a strong bias against the fashion for reusable code. To me, 're-editable code' is much, much better…” ~ Donald Knuth

Related PowerShell Commands:

Set-Variable - Set a variable and its value.
Operators - Format strings and arrays @( ) -f [ ] $( ) :: &
Functions - Write a named block of code.
CMD Shell: Batch file macros

Copyright © SS64.com 1999-2019
Some rights reserved