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


