liveBook · Manning

Script block

As explained in Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS

A script block is a PowerShell language construct that groups executable statements inside braces for invocation or deferred execution.

A script block groups executable PowerShell statements inside curly braces. It can run immediately as part of a command, or be stored in a variable and invoked later with the call operator (&). Hash tables also use braces, but an @ symbol distinguishes them from script blocks. section 26.7

Script blocks commonly provide the work performed by other PowerShell commands:

  • Where-Object uses a filter script block to decide which objects continue through the pipeline. section 26.7
  • ForEach-Object runs its process script block once for every piped object; $_ represents the current object. section 15.3.1 section 15.5.4
  • Select-Object can use a script block as the Expression value for a calculated property, with $_ providing access to the original object. section 10.5
  • Invoke-Command and Start-Job accept script blocks for remoting and job-related work. section 26.7

Store and run a block

Assign several commands to $block, then invoke the saved work with &$block. This separates defining the commands from executing them; the example lists processes by virtual memory and selects the first ten. section 26.7

Run once for each object

Get-Content -Path vaultsToCreate.txt | ForEach-Object { New-AzKeyVault -ResourceGroupName manning -Location 'UK South' -Name $_ } runs the block for each vault name, passing the current value through $_. section 15.3.1

1..5 | ForEach-Object -parallel {Write-Output "$_"; start-sleep -Seconds 2}

Compare sequential and parallel ForEach-Object execution through a script block that writes each number and pauses. section 23.1.3

How Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS covers it

How deep it goes
Explains braces, $_, invocation, and common command parameters, then extends processing to parallel execution and throttle limits.
Examples
Demonstrates process reporting, CSV-derived user properties, Azure Key Vault creation, array iteration, and parallel timing.
What it assumes
Assumes basic PowerShell commands and pipelines while teaching braces, pipeline objects, $_, and deferred execution directly.
What you can do after
Builds reusable command groups and applies them to pipeline objects through ForEach-Object, $_, and the call operator.
How it connects
Connects script blocks with pipelines, variables, call operators, hash tables, calculated properties, remoting, jobs, and loops.

Also explained in

Compare how 3 books explain script block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS. The section links point to the parts of the book it draws on.