PowerShell Scripts: Functions, Parameters & Errors

Advanced functions with validated parameters, returning objects, try/catch/finally and exit codes.

PowerShell functions declare their parameters with types, defaults and validation rules, and return objects that other commands can use. Errors are handled with try/catch like in C# or Python.

A reusable function and error handling

param(...) declares typed parameters; [Parameter(Mandatory)] makes one required; [ValidateSet(...)] restricts values.

[pscustomobject]@{...} returns a real object, displayed here with Format-List.

-ErrorAction Stop turns a cmdlet's error into an exception that try/catch can handle.

Calling the function with rev_z fails validation before its body runs.

$LASTEXITCODE holds the exit code of the last external program.

Running scripts

try { Get-Content missing.log } catch { 'never runs' } try { Get-Content missing.log -ErrorAction Stop } catch {... }

Most cmdlet errors are non-terminating: they print an error and continue, so catch never sees them unless you add -ErrorAction Stop.

Why return objects instead of formatted strings from functions?

Callers can then filter, sort, export or format the results themselves; strings would have to be parsed again.