Cyber Intelligence
Data and Scripting Basics · Core scripting

L5. Control Flow and Functions

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:

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' }
}

Functions

Functions turn repeated command sequences into reusable tools:

function Get-ProcessHealth {
  param(
    [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.

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 $_ })].
  4. Return a [pscustomobject], not formatted text.
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?

Recommended: Pluralsight

This free course covers the theory. Pluralsight adds structured video courses, hands-on Azure labs, and timed practice exams to make it stick before exam day.

Start AZ-500 prep free10-day free trial available