liveBook · Manning

Script block

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

A script block is a PowerShell expression that groups commands and can be passed, stored, or invoked as a unit.

A script block groups PowerShell commands inside curly brackets so the code can be stored without executing immediately. It can later be converted to a string or passed as a parameter, while retaining syntax highlighting, IntelliSense, and code analysis. section 11.4.3

Script blocks are useful when automation must preserve executable code while generating or registering scripts:

  • Convert the block to text with ToString() when writing a .ps1 file. section 11.4.3

Registering deferred Git configuration

$ScriptBlock = { git config --global init.defaultBranch main git config --global --list } New-ActiveSetup -Name 'Git' -ScriptBlock $ScriptBlock -Version '1.0'

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Explains declaration, deferred execution, string conversion, and function passing, but stops short of execution-context internals.
Examples
Demonstrates deferred Git configuration passed to New-ActiveSetup and written into a versioned ProgramData script.
What it assumes
Assumes familiarity with PowerShell commands, variables, functions, and Active Setup registration.
What you can do after
Build reusable deferred automation by storing command groups, passing them to functions, and serializing them into script files.
How it connects
Connects script blocks with here-strings, functions, Active Setup, registry configuration, and Git setup.

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 Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.