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
- Write a function that accepts a path and returns file count and total size.
- Add
[Parameter(Mandatory)]to the path. - Add
[ValidateScript({ Test-Path $_ })]. - Return a
[pscustomobject], not formatted text.
- ✓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
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.