🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Script Structure

Script structure is the order of parts in a script. Parameters come first, functions come next, and the main flow comes last.

The param block goes first

A param block at the top names the values the script accepts. A default value keeps the script runnable with no arguments.

param([string]$Name = "Ana")
"Hello, $Name"

Begin, process, and end inside a function

The begin block sets up, the process block does the work, and the end block finishes. Each block has one job.

function Get-ReportLine {
  param([string]$Title)
  begin { $lines = @() }
  process { $lines += "Report: $Title" }
  end { $lines -join ", " }
}
Get-ReportLine -Title "Weekly"

Functions before the main flow

Define each function above the main flow that uses it. The main flow at the bottom then reads like a short list of steps.

function New-Line {
  param([string]$Text)
  "Line: $Text"
}
$lines = @()
$lines += New-Line -Text "Hello, Ana"
$lines += New-Line -Text "Tasks: 3"
$lines -join ", "

Example

param([string]$Name = "Ana")
function New-Report {
  param([string]$Title)
  begin { $lines = @() }
  process { $lines += "Report: $Title" }
  end { $lines -join ", " }
}
$report = New-Report -Title "Weekly for $Name"
$report
"Report done"

Key points

  • Script structure: the order of parts in a script, from parameters at the top to the main flow at the bottom.
  • Parameters: values a script accepts at the top, in a param block.
  • Setup: the begin block runs once before the main work starts.
  • Work: the process block runs the main work of a function.
  • Cleanup: the end block runs once after the work finishes.
  • Function order: define a function above the line that calls it, so the reader meets it first.

In this example, the param block comes first, then the function with its setup, work, and finish blocks, and the main flow at the bottom calls the function and prints the report.

Note

a script with a param block must put the param block first, before any other code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which order is correct for a well-structured script?