PowerShell Script Blocks
A script block is a piece of code inside braces { } that you can store in a variable, pass to a command and run later. You've already used many: the { $_ -gt 3 } in Where-Object, the body of ForEach-Object, the Expression of a calculated property. Script blocks are PowerShell's anonymous functions, or "lambdas".
Creating and running
Run a stored script block with the call operator & or its .Invoke() method:
$sayHello = { 'Hello from a script block' }
& $sayHello
$sayHello.Invoke()
$sayHello.GetType().Name
$sayHello.ToString()Hello from a script block
Hello from a script block
ScriptBlock
'Hello from a script block'
Printing the block (or calling .ToString()) shows its source code; only & actually runs it.
Parameters and $args
Script blocks take parameters exactly like functions, with a param() block or through $args:
$area = {
param([double]$Width, [double]$Height)
$Width * $Height
}
& $area 3 4
& $area -Width 2.5 -Height 2
$sum = { ($args | Measure-Object -Sum).Sum }
& $sum 10 20 3012
5
60
Passing code to functions
Because a script block is a value, a function can accept code as a parameter and decide when to run it. This is how you build your own "higher-order" helpers:
function Invoke-WithTiming {
param([string]$Label, [scriptblock]$Action)
"[$Label] start"
& $Action
"[$Label] done"
}
Invoke-WithTiming -Label 'backup' -Action {
' copying files...'
' compressing...'
}
function Invoke-Retry {
param([scriptblock]$Action, [int]$Times = 3)
for ($i = 1; $i -le $Times; $i++) {
try { return & $Action $i }
catch { " attempt $i failed: $($_.Exception.Message)" }
}
'giving up'
}
Invoke-Retry -Action {
param($attempt)
if ($attempt -lt 3) { throw 'server busy' }
" succeeded on attempt $attempt"
}[backup] start
copying files...
compressing...
[backup] done
attempt 1 failed: server busy
attempt 2 failed: server busy
succeeded on attempt 3
Script blocks as predicates and calculations
Many cmdlets take a script block to decide something per object. You can keep such blocks in variables and reuse them:
$isExpensive = { $_.Price -gt 100 }
$withTax = @{ Name = 'Gross'; Expression = { [math]::Round($_.Price * 1.2, 2) } }
$products = @(
[pscustomobject]@{ Name = 'Mouse'; Price = 25 }
[pscustomobject]@{ Name = 'Monitor'; Price = 240 }
[pscustomobject]@{ Name = 'Desk'; Price = 410 }
)
$products | Where-Object $isExpensive | Select-Object Name, Price, $withTax
Name Price Gross
---- ----- -----
Monitor 240 288.00
Desk 410 492.00
Closures: capturing variables
A script block reads variables when it runs, not when it's created. To freeze the current values, call .GetNewClosure():
$makers = foreach ($factor in 2, 3) {
{ param($x) $x * $factor }.GetNewClosure()
}
$factor = 100
& $makers[0] 5
& $makers[1] 5
& { param($x) $x * $factor } 510
15
500
Without GetNewClosure(), both stored blocks would see the final $factor value (100).
Call operator vs dot-sourcing
& { } runs the block in a new child scope: variables created inside disappear afterwards. The dot operator . { } runs it in the current scope:
$counter = 1
& { $counter = 50; "inside &: $counter" }
"after &: $counter"
. { $counter = 50; "inside .: $counter" }
"after .: $counter"inside &: 50
after &: 1
inside .: 50
after .: 50
The same two operators run script files: & ./tool.ps1 keeps its variables private; . ./helpers.ps1 loads its functions and variables into your session (see Scripts & Scopes).
Note: To turn a string into a script block, use
[scriptblock]::Create('Get-Date'). Be careful with text you didn't write yourself: running it is as dangerous asInvoke-Expression.
Test yourself
How do you run the script block stored in $job?
- $job
- & $job
- run $job
- $job()
What does .GetNewClosure() do?
- Runs the block in parallel
- Copies the current values of the variables it uses into the block
- Makes the block read-only
- Converts it to a string
After $x = 1; & { $x = 2 }, what is $x?
- 1
- 2
- $null
- An error