Protego field desk
Data and Scripting Basics · Core scripting

L5. Control Flow and Functions

Course outlineLesson 5 of 10
PowerShell Zero to Hero: course overview

Write reusable scripts with if statements, switch, loops, functions, parameters, validation attributes, and pipeline-friendly output.

Control Flow

PowerShell supports familiar conditional and loop patterns. The Get-Service example requires Windows; use Get-Process for a cross-platform loop exercise:

if (Test-Path .\config.json) {
  'Config found'
} else {
  'Config missing'
}

foreach ($service in Get-Service) {
  if ($service.Status -eq 'Stopped') {
    $service.Name
  }
}
switch is useful when several cases share the same input:

switch ($env:OS) {
  'Windows_NT' { 'Windows host' }
  default { 'Non-Windows or unknown host' }
}

Each matching switch clause can run. Use break to stop after a match; continue moves to the next input item when switch processes a collection.

Functions

Functions turn repeated command sequences into reusable tools. [CmdletBinding()] enables common parameters such as -Verbose:

function Get-ProcessHealth {
  [CmdletBinding()]
  param(
    [ValidateRange(1, 100)]
    [int]$Top = 5
  )

  Get-Process |
    Sort-Object CPU -Descending |
    Select-Object -First $Top Name, Id, CPU
}

Get-ProcessHealth -Top 10

Parameter Validation

function Test-PortRange {
  param(
    [Parameter(Mandatory)]
    [ValidateRange(1, 65535)]
    [int]$Port
  )

  [pscustomobject]@{
    Port = $Port
    Valid = $true
  }
}

Validation catches bad input at the boundary of your function instead of letting the error appear several steps later.

Output Rule

Write objects to the pipeline. Avoid Write-Host for data that another command might need. Use Write-Verbose, Write-Warning, or Write-Information for messages.

Every uncaptured expression writes to the success stream, even before a return statement. return exits the current function; it does not suppress earlier output. For pipeline input, add a ValueFromPipeline parameter and process block rather than assuming a function accepts pipeline input automatically.

Lab

  1. Write a function that accepts a path and returns file count and total size.
  2. Add [Parameter(Mandatory)] to the path.
  3. Add [ValidateScript({ Test-Path -LiteralPath $_ -PathType Container })].
  4. Return a [pscustomobject], not formatted text.

References

Continue Learning

Handle errors and files

Exam Focus Points
  • ✓Use if/elseif/else for branching and switch for multiple cases
  • ✓Functions should accept parameters and return objects where possible
  • ✓Parameter validation catches bad input early
  • ✓Write-Host is for display, not structured output
  • ✓Pipeline-friendly functions are easier to test, export, and compose
Knowledge Check

1. Which attribute makes a function parameter required?

2. Why should automation functions usually return objects instead of formatted strings?