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


