liveBook · Manning

Script block

As explained in Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

A script block is a grouped sequence of PowerShell statements enclosed in braces that can be executed as a unit.

A script block is a grouped sequence of PowerShell statements enclosed in braces and executed as a unit. Control-flow constructs attach script blocks to conditions, cases, collections, or loops. section 5.2 section 5.3

Use script blocks in several common constructs:

  • Attach one to If, ElseIf, or Else to run statements when a Boolean expression matches. section 5.2
  • Place one inside ForEach to process each item in a collection, with the current item available through a variable. section 5.3
  • Associate one with each Switch condition or default case; matching blocks execute, and multiple conditions can match. section 5.4
  • Repeat one with While or Do/While, taking care to ensure the condition eventually becomes false. section 5.5

Conditional action

if ($proc.vm -gt 4) { # take some action } elseif ($proc.vm -lt 2) { # take some other action } else { # nothing was true; do this instead } Only the first true If or ElseIf branch runs; Else runs when no preceding expression is true. Keep multi-line blocks clearly formatted, even though PowerShell permits compact brace placement. section 5.2

If (<expression>) {
    # code
} ElseIf (<expression>) {
    # code
} ElseIf (<expression>) {
    # code
} Else {
    # code
}

Compare the complete If structure, including its conditional script blocks and optional ElseIf and Else branches. section 5.2

How Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools covers it

How deep it goes
Defines syntax and execution behavior across four constructs, but defers deeper script-block internals.
Examples
Demonstrates conditional branches, service iteration, wildcard switch matching, and repeated loops.
What it assumes
Assumes PowerShell expressions and Boolean conditions, while demonstrating the required brace-delimited grouping from examples.
What you can do after
Apply it via PowerShell control-flow constructs to group actions, process collections, select cases, and repeat operations.
How it connects
Connects script blocks to If statements, ForEach loops, switch statements, and While 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 Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools. The section links point to the parts of the book it draws on.