PowerShell Lesson 3: Functions, Scope and Advanced Functions
[CmdletBinding()] gives it common parameters and strict binding, how to declare typed, validated, completable parameters, how to accept pipeline input correctly, and how to document and type its output — ending with the first three OpsKit commandsGet-Content in Lesson 1 now applies to your own functions, because an advanced function is bound by the same engine as a compiled cmdlet. OpsKit milestone: the course project starts here as v0.1 — three loose functions in ~/pslab/OpsKit (Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint) loaded by a dot-sourced loader. Lesson 4 packages them as a real module.- Predict a function's output: every value that is not captured goes to the success stream (including
ArrayList.Add's index),returnonly exits, and collections are unrolled unless you use the comma operator orWrite-Output -NoEnumerate. - Explain dynamic scope: a child scope reads parent variables, an assignment creates a local copy,
$script:/$global:/$private:change that, dot-sourcing runs in the caller's scope, and$using:crosses into parallel runspaces. - Turn a function into an advanced function with
[CmdletBinding()]and use what it adds: common parameters,Write-Verbose,$PSCmdlet,$PSBoundParameters, and rejection of unknown parameters. - Declare parameters precisely: types, Mandatory, Position, defaults,
[switch], aliases and parameter sets withDefaultParameterSetName. - Validate input at the boundary with
Validate*attributes (and customErrorMessage), and add tab completion withArgumentCompleterandRegister-ArgumentCompleter. - Write pipeline-aware functions:
ValueFromPipelinevsValueFromPipelineByPropertyName, begin / process / end, aliases such as[Alias('IP')]— this lesson's core animation — and prove binding withTrace-Command. - Make output and usage discoverable:
[OutputType], PSTypeName, comment-based help in the right place, splatting and$PSBoundParametersforwarding, and approved verbs. - Build and verify OpsKit v0.1:
Get-OpsServer -Env prod | Test-OpsEndpointruns end to end against the inventory and a local TCP listener, with acceptance checks and exit codes.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interactive | Lab (~/pslab) |
|---|---|---|---|---|---|
| 0 | Before Class | OpsKit skeleton | ~/pslab/OpsKit with Public/, Private/, tests/ and a dot-sourcing loader OpsKit.ps1; warm-up on Lesson 1's $args bug | Self-check checklist | Create the skeleton and load a test function |
| 1 | 00–06 | Functions and output | function, param(), calling syntax (f a b not f(a,b)), implicit output, $null = / [void] / Out-Null, return, unrolling, , and -NoEnumerate | Output collector: what lands on the success stream | Reproduce the ArrayList index leak and fix it three ways |
| 2 | 06–13 | Scope | Global, script, local, private; read-through vs copy-on-assign; Get-Variable -Scope; dot-sourcing scripts and functions; $using:; closures | Scope stack: where does this variable live? | Reproduce “the counter did not stick” |
| 3 | 13–21 | Advanced functions | [CmdletBinding()], the 12 common parameters, Write-Verbose/-Verbose, -ErrorAction, $PSCmdlet, $PSBoundParameters, strict parameter binding | Simple vs advanced: the same call, two outcomes | Upgrade a simple function and watch -Nmae fail loudly |
| 4 | 21–28 | Parameters | Types and conversion, Mandatory, AllowEmptyString, Position, default expressions, [switch], parameter sets, DefaultParameterSetName, aliases | Parameter-set resolver | Design Get-Node with three parameter sets |
| 5 | 28–35 | Validation and completion | ValidateSet, ValidatePattern, ValidateRange, ValidateScript, ValidateNotNullOrEmpty, ValidateCount/Length, ErrorMessage, ArgumentCompleter, Register-ArgumentCompleter | Validation gate: which attribute stops this value? | Completers proven with TabExpansion2 |
| 6 | 35–42 | Pipeline input | ValueFromPipeline vs ValueFromPipelineByPropertyName, begin / process / end, the missing-process bug, [string[]] + foreach, [Alias('IP')], coercion traps | core animation: binding into your own function | Make servers.csv rows bind to -Target |
| 7 | 42–50 | Output and help | [OutputType], PSTypeName and Update-TypeData, [PSTypeName()] parameters, comment-based help placement, splatting, $PSBoundParameters forwarding, approved verbs | Help-block placement checker | Help for OpsKit; a forwarding wrapper |
| 8 | 50–60 | OpsKit v0.1 | Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint, loader, local TcpListener | Endpoint test walk-through + troubleshooting tree | Write the three functions |
| — | After Class | Cheat sheet · Integrated lab | Use OpsKit end to end: Get-OpsServer -Env prod | Test-OpsEndpoint; acceptance script Invoke-OpsKitCheck.ps1 with exit codes | Final quiz (12 questions) | All 13 checks pass |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Predict function output and unrolling | ✓ | · | · | · | · | ✓ | ✓ | ✓ | $null =, [void], return, ,$a, -NoEnumerate | M1 |
| Reason about scope and dot-sourcing | · | ✓ | · | · | · | · | · | ✓ | $script:, $global:, $private:, . ./x.ps1, $using: | M2, M8 |
| Write advanced functions | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | [CmdletBinding()], $PSCmdlet, $PSBoundParameters | M3, integrated lab |
| Design parameters and parameter sets | ✓ | · | ✓ | ✓ | ✓ | · | · | ✓ | [Parameter(Mandatory, Position, ParameterSetName)], [switch], [Alias()] | M4 |
| Validate and complete arguments | · | · | · | ✓ | ✓ | · | · | ✓ | [ValidateSet()], [ValidateScript()], Register-ArgumentCompleter, TabExpansion2 | M5, integrated lab |
| Accept pipeline input correctly | · | · | · | · | · | ✓ | ✓ | ✓ | ValueFromPipeline(ByPropertyName), process {}, Trace-Command | M6, integrated lab |
| Document, type and forward | · | · | ✓ | · | · | · | ✓ | ✓ | [OutputType()], PSTypeName, <# .SYNOPSIS #>, @params, Get-Verb | M7 |
| Build and verify a small toolkit | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | Import-PowerShellDataFile, TcpClient, TcpListener, exit codes | M8, integrated lab |
Excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
Script modules (.psm1), manifests, Export-ModuleMember, module scope, real private functions, format files (.format.ps1xml), publishing | Packaging comes after you have functions worth packaging | Lesson 4: Modules, Packages, Providers (OpsKit v0.2) |
try/catch/finally in depth, terminating vs non-terminating errors, $ErrorActionPreference, streams 1–6, SupportsShouldProcess / -WhatIf / -Confirm, Set-StrictMode | This lesson only uses them where a function needs them; safe change is its own topic | Lesson 5: Robust Scripts (OpsKit v0.3) |
ForEach-Object -Parallel, jobs, runspaces, remoting ($using: is only previewed here) | Concurrency and remote execution | Lesson 6 (OpsKit v0.4) |
PowerShell classes, enums, DynamicParam | Rarely needed for tool functions; dynamic parameters are hard to test and discover | Mentioned in Lesson 4; see about_Classes, about_Functions_Advanced_Parameters |
| Pester tests, PSScriptAnalyzer rules, debugging with breakpoints | Quality tooling; this lesson uses a simple acceptance script instead | Lesson 8 (OpsKit v1.0) |
How to use these materials
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Read “Principles” and “Animation” first, then do the “Lab” in
~/pslab. The pipeline-input animation in Module 6 continues Lesson 1's binding animation — with your own function on the receiving end.A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
ErrorMessage on ValidateScript/ValidatePattern (PowerShell 6+) and [ValidateNotNullOrWhiteSpace()] (7.4+). ProgressAction became the 12th common parameter in 7.4. In Windows PowerShell 5.1 the function language is the same, but ErrorMessage, the null-coalescing operator and ForEach-Object -Parallel do not exist. TCP results in Module 8 depend on the operating system's network stack; the Windows-specific timings are marked.Module 0 · Prep: the OpsKit project skeleton
~/pslab/OpsKit with Public/, Private/ and tests/, plus a small loader OpsKit.ps1 that dot-sources every function file — the v0.1 layout that Lesson 4 turns into a real module- Lesson 1 completed:
~/pslab/dataexists (rebuild it with~/pslab/New-LabData.ps1if needed) and you know how pipeline binding works (ByValue, then ByPropertyName). - Lesson 2: arrays, hashtables,
[pscustomobject],ConvertFrom-JsonandImport-PowerShellDataFile. - PowerShell 7.6 (7.4 works too) and VS Code with the PowerShell extension. No administrator rights, no internet access and no cloud account are needed for this lesson.
Warm-up: answer from memory (30 seconds)
1. In Lesson 1's integrated lab, New-Check 'envs' 'a,b' ('b','a' | Sort-Object) -join ',' reported a b instead of a,b. Why did nothing complain about the extra -join and ','?
New-Check was a simple function (function New-Check([string]$Name, $Expected, $Actual)). In argument mode -join is just a word that looks like a parameter name; a simple function puts unknown arguments into $args and ignores them. Module 3 shows that adding [CmdletBinding()] turns this silent bug into an immediate error.
function New-Check([string]$Name, $Expected, $Actual) { "$Name expected=$Expected actual=$Actual" }
New-Check 'envs' 'a,b' ('b', 'a' | Sort-Object) -join ','
(Get-Command New-Check).CmdletBinding
envs expected=a,b actual=a b False
2. Get-Item ./data/servers.csv | Get-Content works, './data/servers.csv' | Get-Content fails. Which binding rule explains it?
FileInfo binds ByPropertyName: its PSPath property matches an alias of -LiteralPath. A plain string has no such property, and Get-Content has no ByValue parameter. In this lesson you will give your own parameters aliases ([Alias('IP')]) for exactly the same effect.
3. What is the difference between & ./lib.ps1 and . ./lib.ps1?
The call operator runs the script in a new script scope that is discarded afterwards; dot-sourcing runs it in the caller's scope, so its functions and variables stay. The OpsKit loader depends on this (Module 2).
Step 1 — create the skeleton
$kit = Join-Path $HOME 'pslab' 'OpsKit'
'Public', 'Private', 'tests' | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path $kit $_) -Force } | Out-Null
Get-ChildItem $kit -Name
Private Public tests
| Path | Contents in v0.1 (this lesson) | What changes later |
|---|---|---|
OpsKit/Public/ | One file per user-facing function: Get-OpsServer.ps1, Get-OpsConfig.ps1, Test-OpsEndpoint.ps1 | Lesson 4 exports exactly these from the module manifest |
OpsKit/Private/ | Helpers such as Get-OpsDataPath.ps1 | Lesson 4 makes them truly private (module scope); in v0.1 they are visible because everything is dot-sourced into your session |
OpsKit/tests/ | Invoke-OpsKitCheck.ps1, a plain acceptance script (integrated lab) | Lesson 8 replaces it with Pester 6 tests and CI |
OpsKit/OpsKit.ps1 | The loader: dot-sources Private/*.ps1, then Public/*.ps1 | Replaced by OpsKit.psd1 + OpsKit.psm1 in Lesson 4 |
Step 2 — the loader OpsKit.ps1
Save this as ~/pslab/OpsKit/OpsKit.ps1. Two details matter: the foreach statement does not create a scope, so . $file.FullName defines each function in the loader's own scope; and because you dot-source the loader, that scope is your session. Run it with & instead and the functions vanish when the loader returns (Module 2 reproduces this).
# OpsKit v0.1 loader. Dot-source it to load every function into your session:
# . ~/pslab/OpsKit/OpsKit.ps1
# Running it with & or ./ loads the functions into a script scope that disappears
# when the loader ends (Module 2). Lesson 4 replaces this file with OpsKit.psd1 + OpsKit.psm1.
foreach ($folder in 'Private', 'Public') {
$dir = Join-Path $PSScriptRoot $folder
foreach ($file in Get-ChildItem -LiteralPath $dir -Filter *.ps1 -File) {
. $file.FullName
}
}
Step 3 — prove the loader works with a throw-away function
Set-Content ~/pslab/OpsKit/Public/Get-OpsHello.ps1 -Value 'function Get-OpsHello { "OpsKit loaded from $PSScriptRoot" }'
. ~/pslab/OpsKit/OpsKit.ps1
Get-OpsHello
Get-ChildItem ~/pslab/OpsKit -Recurse -File | ForEach-Object { $_.FullName.Substring($HOME.Length + 1) }
Remove-Item ~/pslab/OpsKit/Public/Get-OpsHello.ps1
OpsKit loaded from C:\Users\labadmin\pslab\OpsKit\Public pslab\OpsKit\OpsKit.ps1 pslab\OpsKit\Public\Get-OpsHello.ps1
Note what $PSScriptRoot means inside a function: the folder of the file that defined the function (Public), not the loader's folder and not your current location. Lesson 4 relies on this for module-relative paths.
Step 4 — check the data the functions will read
(Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json).Count (Import-PowerShellDataFile ~/pslab/data/opskit.config.psd1).Environments.Keys | Sort-Object
12 dev prod staging
Environment self-check checklist
~/pslab (OpsKit/, scripts/, tmp/). Module 8 opens a TCP listener on 127.0.0.1:18080 only — loopback, not reachable from the network — and stops it in the same step; if port 18080 is busy on your machine, use any free port above 1024. The 10.x addresses in the inventory are fictitious: connecting to them produces timeouts, which is expected and harmless. To start over: Remove-Item -LiteralPath ~/pslab/OpsKit -Recurse -Force and repeat Steps 1–2. Keep the folder afterwards — Lessons 4–8 build on it.Module 1 · Functions: definition, parameters and output semantics
return. Getting this one rule right prevents a whole family of “why is there a 0 1 2 in my result?” bugs- Define functions with a
param()block and call them PowerShell-style:Add-Two 1 2, neverAdd-Two(1, 2). - State the output rule: every expression or command result that is not assigned, cast to
[void]or redirected goes to the success stream — including the return values of .NET methods such asArrayList.Add()andStringBuilder.Append(). - Use
returnonly to leave a function early, and suppress unwanted output with$null =,[void]or| Out-Null(and know which is slowest). - Predict unrolling: an empty array becomes nothing (
$null), a one-element array becomes a scalar, aList[T]becomesObject[]; keep a collection intact with,$xorWrite-Output -NoEnumerate, and protect callers with@( ).
What: a function is a named script block
function Get-Greeting { param([string]$Name = 'world') "Hello, $Name" } creates an entry in the Function: drive. When you call it, PowerShell creates a new child scope, binds arguments to the param() variables, runs the body, and streams every output object to the caller as it is produced. Two definition styles exist and are equivalent for simple functions:
| Style | Example | Use it for |
|---|---|---|
| Inline parameter list | function Add-Two($a, $b) { $a + $b } | Tiny helpers; cannot hold attributes such as [CmdletBinding()] |
param() block | function Add-Two { param([int]$A, [int]$B) $A + $B } | Everything else — it is the only style that becomes an advanced function (Module 3) |
Calling syntax is command syntax, not method syntax: arguments are separated by spaces. Add-Two(1, 2) passes one argument — the array 1, 2 — to $a, and leaves $b empty. In 7.6 this does not even raise an error; you just get a strange result.
Why: the output rule
PowerShell has no single “return value”. A function's result is the success stream: every value that is not assigned to a variable, cast to [void], piped to Out-Null or redirected. That includes values you did not mean to emit:
| Line inside a function | What it silently outputs | Fix |
|---|---|---|
$list.Add('web-01') (ArrayList) | The new index: 0, 1, 2… | $null = $list.Add(…) or use List[string], whose Add() returns void |
$sb.AppendLine('x') | The StringBuilder itself | [void]$sb.AppendLine('x') |
New-Item -ItemType Directory … | A DirectoryInfo object | $null = New-Item … |
$hash.Remove('k') on $PSBoundParameters | True | $null = … |
Write-Host 'checking' | Nothing — goes to the host (information stream) | Correct for messages; never use for data |
How: return, unrolling and keeping collections
return 'x' is shorthand for “output 'x', then exit”. Everything output before it is still part of the result. When a function outputs a collection, the pipeline enumerates it (one object at a time, Lesson 1 Module 5); when the caller assigns the result, PowerShell collects the stream again: nothing → $null (strictly, AutomationNull), one item → that item, several → Object[]. The original collection type (List[string], ArrayList) is lost.
| The function ends with | $r = f gives | To keep the collection |
|---|---|---|
@() | $null | ,@() or caller writes @(f) |
@('web-01') | [string] 'web-01' | ,@('web-01') |
@('a','b') | Object[] | (already an array) |
a List[string] | Object[] | Write-Output $list -NoEnumerate or ,$list |
When: which convention to choose
For tool functions (like OpsKit), emit objects one at a time and let the caller collect — that streams and works with Select-Object -First. Use -NoEnumerate/comma only when the caller genuinely needs one collection object (rare: e.g. a function that returns a lookup table). On the caller side, wrap results in @( ) whenever you need .Count or indexing to be reliable for 0, 1 or many results.
return produces output” — every uncaptured value does; return just exits. ② “f(1, 2) passes two arguments” — it passes one array. ③ “My function returns a List, so the caller gets a List” — the caller gets Object[] (or a scalar, or $null). ④ “Write-Host output is part of the result” — it is not captured by $x = f. ⑤ “Out-Null is the idiomatic way” — it works, but $null = is about twice as fast in a tight loop (measured below).Diagram: what reaches the caller
Diagram: unrolling on the way out
Output collector: what lands on the success stream?
Choose a function and step through its lines. Green = emitted to the success stream, yellow = executed but not output, red = surprising output or result. All results were reproduced on PowerShell 7.6.10.
Command reference
| Syntax | Purpose | Notes |
|---|---|---|
function Verb-Noun { param(…) … } | Define a function | Lives in Function:; Get-Command Verb-Noun shows it |
Verb-Noun -Name x / Verb-Noun x | Call it | Spaces between arguments, no parentheses, no commas |
$null = expr | Discard a value | Fastest; reads well |
[void]expr | Discard a value | Only for expressions, not for commands |
cmd | Out-Null | Discard pipeline output | Slowest of the three |
return $x | Output $x and leave | Earlier output is kept |
, $array / Write-Output $x -NoEnumerate | Emit a collection as one object | Rarely needed |
@(f) | Always get an array from a call | Caller-side safety for .Count |
Get-Item Function:\Verb-Noun, Remove-Item Function:\… | Inspect / delete a function | The Function provider (Lesson 4) |
function Get-Greeting {
param([string]$Name = 'world')
"Hello, $Name"
}
Get-Greeting
Get-Greeting -Name ops
Get-Greeting ops
Get-Command Get-Greeting | Format-List Name, CommandType, Definition
Hello, world
Hello, ops
Hello, ops
Name : Get-Greeting
CommandType : Function
Definition :
param([string]$Name = 'world')
"Hello, $Name"
function Add-Two($a, $b) { $a + $b }
Add-Two 1 2
Add-Two(1, 2)
Add-Two(1, 2) | ForEach-Object { "item: [$_]" }
3 1 2 item: [1] item: [2] item: []
How to verify: the third item is $null: $a received the array 1, 2, and @(1,2) + $null appends a null element. Common mistake: calling functions like C# methods, especially by people coming from Python or JavaScript. Production use: once a function is advanced (Module 3), a typed parameter such as [int]$A would reject the array with a clear conversion error instead of producing garbage.
function Get-Names {
$list = [System.Collections.ArrayList]::new()
foreach ($n in 'web-01', 'api-01', 'db-01') { $list.Add($n) }
"found $($list.Count) names"
}
Get-Names
$r = Get-Names
$r.Count
$r[0].GetType().Name
0 1 2 found 3 names 4 Int32
function New-Report {
$sb = [System.Text.StringBuilder]::new()
$sb.AppendLine('# Report') # leaks the StringBuilder
[void]$sb.AppendLine('servers: 12')
$sb.ToString()
}
(New-Report).Count
New-Report | ForEach-Object { $_.GetType().Name }
2 StringBuilder String
$list = [System.Collections.ArrayList]::new()
'{0,-10} {1,6:N0} ms' -f '$null =', (Measure-Command { foreach ($i in 1..100000) { $null = $list.Add($i) } }).TotalMilliseconds
'{0,-10} {1,6:N0} ms' -f '[void]', (Measure-Command { foreach ($i in 1..100000) { [void]$list.Add($i) } }).TotalMilliseconds
'{0,-10} {1,6:N0} ms' -f '| Out-Null', (Measure-Command { foreach ($i in 1..100000) { $list.Add($i) | Out-Null } }).TotalMilliseconds
$null = 605 ms [void] 653 ms | Out-Null 1,202 ms
The cost of | Out-Null is the pipeline set-up per call. It matters only in loops with tens of thousands of iterations; in ordinary code, choose the form your team reads best — but be consistent.
Goal: Reproduce each output surprise and fix it. Environment: pwsh 7.6 in ~/pslab (VS Code or terminal). Cost: none.
Get-Names from the Commands tab and run it. Then fix it three ways:
function Get-NamesFixed {
$list = [System.Collections.ArrayList]::new()
$null = $list.Add('web-01')
[void]$list.Add('api-01')
$list.Add('db-01') | Out-Null
"found $($list.Count) names"
}
Get-NamesFixed
found 3 names
Fourth fix, often the best: $list = [System.Collections.Generic.List[string]]::new() — its Add() returns nothing.
return does not discard earlier output:
function Test-Return {
'one'
return 'two'
'three'
}
Test-Return
$x = Test-Return
$x.Count
one two 2
return with no value is the idiomatic guard clause:
function Get-Env([string]$Name) {
if ($Name -notin 'dev', 'staging', 'prod') { Write-Warning "unknown env $Name"; return }
"env $Name ok"
}
Get-Env prod
Get-Env qa
$null -eq (Get-Env qa 3>$null)
env prod ok WARNING: unknown env qa True
function Get-Zero { @() }
function Get-One { @('web-01') }
function Get-Two { @('web-01', 'api-01') }
function Get-List { $l = [System.Collections.Generic.List[string]]::new(); $l.Add('a'); $l.Add('b'); $l }
$z = Get-Zero; $null -eq $z
(Get-One).GetType().Name
(Get-Two).GetType().Name
(Get-List).GetType().FullName
True String Object[] System.Object[]
-NoEnumerate), and the caller-side alternative @( ):
function Get-OneKept { , @('web-01') }
function Get-ListKept { $l = [System.Collections.Generic.List[string]]::new(); $l.Add('a'); Write-Output $l -NoEnumerate }
(Get-OneKept).GetType().Name
(Get-OneKept).Count
(Get-ListKept).GetType().Name
Get-ListKept | ForEach-Object { "pipeline got: $($_.GetType().Name) with $($_.Count) item(s)" }
@(Get-One).Count
@(Get-Zero).Count
Object[] 1 List`1 pipeline got: List`1 with 1 item(s) 1 0
function Get-Status {
Write-Host 'checking...'
Write-Output 'ok'
'also output'
}
$s = Get-Status
"captured: $($s -join ' | ')"
checking... captured: ok | also output
Remove-Item Function:\Get-Names, Function:\Get-NamesFixed or simply open a new terminal.Case 1: a report e-mailed “0 1 2 3 … 117” before the real data
Problem: A nightly function built a list of stale accounts with ArrayList.Add() and returned it with return $list. The e-mail body started with 118 numbers. Root cause: every Add() wrote its index to the success stream; return only appended the list after them. Fix: List[pscustomobject] (void Add), or $null = $list.Add(…); better still, emit each object directly instead of building a list. Prevention: a test that checks the type of every output object (Lesson 8).
Case 2: “.Count is wrong only when exactly one VM matches”
Problem: $vms = Get-StaleVm; if ($vms.Count -gt 0) { … } worked for 0 and for many VMs, but with one VM a later $vms[0].Name returned the first character of a string property in another variant of the script. Root cause: a single result is not wrapped in an array; when the single object was a string, indexing returned a character. Fix: $vms = @(Get-StaleVm) at the call site. PowerShell 3+ gives scalars a .Count of 1, which hides the problem until you index.
Case 3: a helper that “returned” a DirectoryInfo nobody asked for
Problem: function Get-LogPath { New-Item -ItemType Directory $dir -Force; Join-Path $dir 'run.log' } — callers did Add-Content -Path (Get-LogPath) -Value … and got “Add-Content: Unable to write content because it is a directory: '… mp\logs'.” Root cause: two outputs: the DirectoryInfo and the path string. -Path accepts string[], so both were used as targets and the first one is a folder (reproduced on 7.6.10: (Get-LogPath).Count is 2). Fix: $null = New-Item ….
Common errors and fixes
My function returns extra numbers / objects before the real result
Cause: uncaptured method return values (ArrayList.Add, StringBuilder.Append, HashSet.Add → True/False), or cmdlets like New-Item.
f | ForEach-Object { '{0}: {1}' -f $_.GetType().Name, $_ } # find the intruders
Fix: $null = in front of the offending line.
Unable to write content because it is a directory / a path parameter gets two values
Cause: a function you passed as an argument returned more than one object (see Case 3), or you called a function method-style f(a, b) and passed an array. With a typed advanced function the same mistake fails earlier with “Cannot convert 'System.Object[]' …”.
Fix: inspect with (f).Count and (f) | Get-Member; call with spaces.
.Count or [0] behaves differently for one result
Cause: unrolling — one result is a scalar.
Fix: @(f) on the caller side; or , $result inside the function if the contract is “always one collection”.
The function prints text but $x = f is empty
Cause: the text came from Write-Host (or Format-* output was redirected to the host).
Fix: output data with a bare value or Write-Output; use Write-Verbose for messages (Module 3).
1. Write Get-Port that returns the ports of inventory.json as a List[int] object (not unrolled) and prove the type.
function Get-Port {
$l = [System.Collections.Generic.List[int]]::new()
foreach ($s in (Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json)) { $l.Add($s.Port) }
, $l
}
(Get-Port).GetType().Name # List`1
(Get-Port).Count # 122. Find which line of a function leaks output.
Set-PSDebug -Trace 1; $null = Get-Names; Set-PSDebug -Off # shows each line as it runs
Get-Names | ForEach-Object { $_.GetType().Name } | Group-Object -NoElementThe second line is often enough: 3 Int32, 1 String points straight at the Add() calls.
A teammate says “PowerShell functions are broken: they return everything”. How do you explain the design and when it helps?
Functions are commands, not methods: they write to a stream so that they compose in pipelines and stream results one at a time (memory-friendly, Select-Object -First can stop early). The price is discipline: capture what you do not want to emit ($null =), and do not think of return as “the result”. In exchange, Get-OpsServer | Test-OpsEndpoint starts testing the first server before the last one is read.
Verified teaching videos
No verified video focuses on output semantics (ArrayList leaks, unrolling); rely on this module's reproductions and about_Return.
Official documentation
Video storyboard (about 90 seconds)
Visual: a function as a box with an open chute at the bottom; every line that produces a value drops a token into the chute.
Narration: anything you don't capture falls out of the function.
Visual: ArrayList.Add drops tokens 0, 1, 2; a “$null =” lid covers the chute for that line.
Narration: methods return values too. Discard them with $null equals.
Visual: a crate of one item is unpacked at the exit; a crate wrapped in a second crate (comma) arrives intact.
Narration: collections are unrolled; the comma keeps one level.
Module 2 · Scope: local, script, global, private and dot-sourcing
- Name the scopes — global (the session), script (each script file), local (the current one) and numbered parent scopes — and see them with
Get-Variable -Scope. - Apply the two rules: reading walks up the call chain; assigning without a modifier creates or changes a variable in the current scope only.
- Use
$script:,$global:and$private:deliberately, and prefer return values over shared state. - Explain dot-sourcing of scripts and functions, why the OpsKit loader must be dot-sourced, and how
$using:passes values intoForEach-Object -Parallel(preview of Lesson 6).
& vs .). Importance:★★★★★What: a stack of scopes
Every time a script or function runs, PowerShell pushes a new scope; when it returns, the scope and its variables are discarded. At the prompt you are in the global scope. Running ./x.ps1 pushes a script scope; calling a function inside it pushes a local function scope, and so on.
| Modifier | Refers to | Typical use |
|---|---|---|
(none) / $local: | The current scope for writing; the nearest scope that has the name for reading | Almost everything |
$script: | The scope of the script file (or module, Lesson 4) the code was defined in; at the prompt it is the global scope | State shared by functions of one script/module, e.g. a cache |
$global: | The session | Rarely: values that must survive after a script ends. A code smell in tools |
$private: | Current scope, invisible to child scopes | Keep a secret or a loop variable from leaking into called code |
$using: | A copy of a caller's variable sent to another runspace | ForEach-Object -Parallel, Start-ThreadJob, Invoke-Command (Lesson 6) |
Why: read-through, copy-on-assign
When a function reads $region, PowerShell looks in the current scope, then in the caller's, up to global (dynamic scoping — it follows the call chain, not where the code was written). When the function assigns $region = 'eastus', it creates a new local variable that shadows the parent's; the parent is unchanged. $count++ is a read and an assignment: it reads the parent's 0, then writes 1 into a new local variable — every call.
Bash comparison: Bash functions modify the caller's variables by default unless you declare them local. PowerShell is the opposite: everything you assign is local unless you add a scope modifier.
How: dot-sourcing
The dot operator runs a script or a function in the caller's scope instead of a new one. That is how profiles, libraries and the OpsKit loader leave their functions behind: . ~/pslab/OpsKit/OpsKit.ps1. Inside the loader, . $file.FullName runs each function file in the loader's scope — which is your scope, because you dot-sourced the loader.
When: shared state vs return values
| Need | Prefer | Avoid |
|---|---|---|
| A function computes a new value | Return it: $n = Get-NextCount $n | Modifying $script:n from inside |
| Several functions of one module share a cache | $script:Cache (module scope in Lesson 4) | $global:Cache |
| Load helper functions into the session | Dot-source a file, or import a module | Copy-pasting functions into scripts |
| Pass data into a parallel script block | $using:name (a copy) | Expecting the parallel block to see your variables |
$script: means the script I am running” — it means the script (or module) the function was defined in; at the prompt that is global. ③ “foreach/if blocks have their own scope” — they do not; only scripts, functions, script blocks invoked with &, and modules do. ④ “Script blocks capture variables like closures” — they read the current value at call time unless you call .GetNewClosure(). ⑤ “-Parallel blocks see my variables” — they run in other runspaces; use $using:.Diagram: the scope stack while a function runs
Diagram: call vs dot-source
Scope stack: where does this variable live?
Choose a snippet and watch the scope stack: which scope is read, which is written, and what survives. Results reproduced on 7.6.10.
Command reference
| Command | Purpose | Notes |
|---|---|---|
Get-Variable name -Scope 1 | Read a variable from the parent scope | 0 = current, 1 = parent, Global, Script |
Set-Variable name v -Scope Script | Write into a named scope | Same as $script:name = v |
$script:x, $global:x, $private:x | Scope modifiers | Also for functions: function global:f {} |
. ./file.ps1, . FunctionName | Run in the caller's scope | Space after the dot |
Test-Path variable:name | Does the variable exist (in a visible scope)? | The Variable provider |
$using:name | Copy a value into a parallel/remote block | Read-only copy |
{ … }.GetNewClosure() | Freeze current variable values into a script block | Rare; mostly for event handlers and completers |
$region = 'canadacentral'
function Show-Region { "child sees: $region" }
function Set-Region { $region = 'eastus'; "inside: $region" }
Show-Region
Set-Region
"outside: $region"
child sees: canadacentral inside: eastus outside: canadacentral
$where = 'global'
function Outer {
$where = 'Outer'
function Inner {
"Inner reads `$where = $where"
"scope 1 (Outer): $((Get-Variable where -Scope 1).Value)"
"scope 2 (global): $((Get-Variable where -Scope 2).Value)"
"`$global:where = $global:where"
}
Inner
}
Outer
Inner reads $where = Outer scope 1 (Outer): Outer scope 2 (global): global $global:where = global
How to verify: Inner was defined inside Outer but what matters is the call chain at run time: Outer's scope is scope 1 because Outer called Inner. Common mistake: expecting lexical (C#-style) scoping. Production use: do not rely on reading caller variables in tool functions — pass them as parameters, so the function works the same from any caller.
$private:token = 's3cr3t'
function Show-Token { "child sees token: [$token]" }
Show-Token
"parent sees token: [$token]"
$mode = 'normal'
function Set-Mode { $mode = 'maintenance' }
Set-Mode; "after call: $mode"
. Set-Mode; "after dot-sourcing: $mode"
child sees token: [] parent sees token: [s3cr3t] after call: normal after dot-sourcing: maintenance
$factor = 10
1..3 | ForEach-Object -Parallel { "$_ x factor = $($_ * $factor)" } -ThrottleLimit 1
1..3 | ForEach-Object -Parallel { "$_ x factor = $($_ * $using:factor)" } -ThrottleLimit 1
1 x factor = 0 2 x factor = 0 3 x factor = 0 1 x factor = 10 2 x factor = 20 3 x factor = 30
Without $using:, $factor is $null in the other runspace and $_ * $null is 0 — no error. -ThrottleLimit 1 only keeps the order stable for this demo; Lesson 6 covers parallelism properly.
$threshold = 5
$sb = { "threshold is $threshold" }
& $sb
$threshold = 9
& $sb # reads the CURRENT value
$frozen = { "threshold is $threshold" }.GetNewClosure()
$threshold = 1
& $frozen # value captured when the closure was made
threshold is 5 threshold is 9 threshold is 9
Goal: Reproduce “the variable change did not stick”, fix it two ways, and see why the OpsKit loader must be dot-sourced. Environment: pwsh 7.6, ~/pslab/scripts. Cost: none.
New-Item -ItemType Directory -Path ~/pslab/scripts -Force | Out-Null
Set-Content ~/pslab/scripts/counter.ps1 -Value @'
$count = 0
function Add-Count { $count++; "inside Add-Count: count=$count" }
Add-Count
Add-Count
Add-Count
"after 3 calls: count=$count"
'@
& ~/pslab/scripts/counter.ps1
inside Add-Count: count=1 inside Add-Count: count=1 inside Add-Count: count=1 after 3 calls: count=0
Set-Content ~/pslab/scripts/counter-fixed.ps1 -Value @'
$count = 0
function Add-Count { $script:count++ }
1..3 | ForEach-Object { Add-Count }
"script scope: count=$count"
function Get-NextCount([int]$Current) { $Current + 1 } # better: no shared state
$n = 0
1..3 | ForEach-Object { $n = Get-NextCount $n }
"return value: n=$n"
'@
& ~/pslab/scripts/counter-fixed.ps1
"in my session after the script: count=[$count]"
script scope: count=3 return value: n=3 in my session after the script: count=[]
Note that $n = … inside ForEach-Object { } works: the script block runs in the current scope for ForEach-Object (it is dot-sourced by the cmdlet). Where-Object and ForEach-Object script blocks are the main exceptions to “script blocks get a new scope”.
Set-Content ~/pslab/scripts/lib.ps1 -Value @'
$LibVersion = '1.0'
function Get-LibInfo { "lib $LibVersion" }
'@
& ~/pslab/scripts/lib.ps1
"after &: version=[$LibVersion] function=$([bool](Get-Command Get-LibInfo -ErrorAction Ignore))"
. ~/pslab/scripts/lib.ps1
"after . : version=[$LibVersion] function=$([bool](Get-Command Get-LibInfo -ErrorAction Ignore))"
after &: version=[] function=False after . : version=[1.0] function=True
& ~/pslab/OpsKit/OpsKit.ps1 Get-Command Get-OpsServer
Get-Command: The term 'Get-OpsServer' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
$script: at the prompt is global:
function Set-Last { $global:OpsLastRun = Get-Date -Format 'HH:mm'; $script:OpsMode = 'set by function' }
Set-Last
Test-Path variable:OpsLastRun
$OpsMode
True set by function
Remove-Variable OpsLastRun, OpsMode, LibVersion -ErrorAction Ignore; keep the files in ~/pslab/scripts or delete them.Case 1: a retry counter that never reached its limit
Problem: A deployment script retried an API call with function Invoke-WithRetry { … $attempt++ … if ($attempt -ge 5) { throw } } and $attempt = 0 at script level. It looped forever on a failing endpoint. Root cause: $attempt++ created a local copy each call (always 1). Fix: keep the counter inside the function (a for loop) — Lesson 5 builds a proper retry helper for OpsKit v0.3. Prevention: a function should depend only on its parameters.
Case 2: “works in my console, fails in the scheduled task”
Problem: A function read $ConfigPath without declaring it as a parameter. In the author's console the variable existed (set in his profile); the task ran with -NoProfile and the function got $null. Root cause: dynamic scoping silently read a global variable. Fix: make it a parameter with a default ([string]$ConfigPath = (Join-Path $PSScriptRoot 'config.psd1')). Set-StrictMode -Version Latest (Lesson 5) turns reads of never-set variables into errors.
Case 3: a parallel health check that tested nothing
Problem: $servers | ForEach-Object -Parallel { Test-Connection $_ -TimeoutSeconds $timeout } used the default timeout everywhere. Root cause: $timeout does not exist in the parallel runspaces. Fix: $using:timeout. Lesson 6 uses this pattern in Invoke-OpsHealthCheck.
Common errors and fixes
A variable changed inside a function is unchanged afterwards
Cause: copy-on-assign.
$x = 1
function f { $x = 2; "local: $((Get-Variable x -Scope 0).Value) parent: $((Get-Variable x -Scope 1).Value)" }
f
Fix: return the value; or $script:x for deliberate shared state.
The term 'X' is not recognized … right after running a library script
Cause: the script was run with & or ./, not dot-sourced.
Fix: . ./lib.ps1 (dot, space, path), or turn it into a module (Lesson 4).
A value is $null inside ForEach-Object -Parallel / Start-ThreadJob / Invoke-Command
Cause: different runspace.
Fix: $using:var, or pass -ArgumentList.
The variable '$x' cannot be retrieved because it has not been set.
Cause: Set-StrictMode -Version Latest is on and the name was never assigned in any visible scope — often a typo.
function Get-Total { $total = 0; foreach ($i in 1..3) { $total += $i }; $totla }
Set-StrictMode -Version Latest
Get-Total
InvalidOperation: The variable '$totla' cannot be retrieved because it has not been set.
Without strict mode the same function silently returns nothing.
1. Prove that if and foreach blocks do not create a scope, but a script block called with & does.
$v = 1
if ($true) { $v = 2 }; "after if: $v" # 2
foreach ($i in 1) { $v = 3 }; "after foreach: $v" # 3
& { $v = 4 }; "after & {}: $v" # 3
. { $v = 5 }; "after . {}: $v" # 52. List the variables your current scope defines, without inherited ones.
Get-Variable -Scope 0 | Select-Object -First 10 Name
A colleague's profile defines $Env = 'prod'. Your function Get-OpsServer has a parameter -Env. Is there a conflict when someone calls Get-OpsServer without -Env?
No. A declared parameter is always a variable in the function's own scope; if not supplied, it gets its default ($null here), shadowing the global $Env (verified: it still returns all 12 servers). The danger is the opposite case — an undeclared variable that the function reads by accident. (Note that $Env as a variable and $env:PATH are different things: env: is a drive qualifier.)
Verified teaching videos
Official documentation
- about_Scopes · about_Script_Blocks · about_Remote_Variables ($using:)
Video storyboard (about 90 seconds)
Visual: stacked glass boxes (global, script, function); a hand reaches down through them to read $region.
Narration: reading looks up through every caller.
Visual: writing $count++ makes a copy in the top box; the box is thrown away on return.
Narration: writing creates a local copy — that's why the counter stays zero.
Visual: a dot before a script path merges its box into yours.
Narration: dot-source libraries; return values instead of sharing state.
Module 3 · Advanced functions: [CmdletBinding()], common parameters and $PSCmdlet
-Verbose and -ErrorAction just work, and $PSCmdlet / $PSBoundParameters tell you how you were called- Make a function advanced with
[CmdletBinding()](or any[Parameter()]attribute) and list the 12 common parameters it gains in 7.6. - Contrast binding: a simple function swallows unknown arguments into
$args(Lesson 1's-joinbug); an advanced function rejects them with “A parameter cannot be found …”. - Write diagnostics with
Write-Verbose/Write-Debugand see how-Verbosepropagates to the commands your function calls; honour-ErrorActionwithWrite-Error. - Use
$PSCmdlet(ParameterSetName,MyInvocation,ThrowTerminatingError) and$PSBoundParameters(was a parameter actually passed, or is it the default?).
[<CommonParameters>]). Importance:★★★★★What: an advanced function is a script cmdlet
A function becomes advanced when its param() block carries [CmdletBinding()] or any parameter has a [Parameter()] attribute (verified: (Get-Command f).CmdletBinding is True in both cases). From then on, the same parameter binder that you traced for Get-Content in Lesson 1 binds your function, and the function receives an object $PSCmdlet with most of the API a C# cmdlet has.
| Feature | Simple function | Advanced function |
|---|---|---|
Unknown named argument -Nmae x | Silently added to $args | Error: A parameter cannot be found that matches parameter name 'Nmae'. |
| Extra positional argument | Added to $args | Error: A positional parameter cannot be found that accepts argument … |
| Common parameters | None | 12: Verbose, Debug, ErrorAction, WarningAction, InformationAction, ProgressAction, ErrorVariable, WarningVariable, InformationVariable, OutVariable, OutBuffer, PipelineVariable |
$PSCmdlet | $null | ParameterSetName, MyInvocation, WriteError, ThrowTerminatingError, ShouldProcess (Lesson 5) |
| Parameter attributes | Types only | Mandatory, Position, ValueFromPipeline, parameter sets, validation |
$args | Unbound arguments | Always empty |
Why: fail loudly at the boundary
Lesson 1's integrated lab lost a -join ',' because New-Check was a simple function: the words -join and ',' landed in $args and nobody looked there. An advanced function turns the same mistake into an immediate, precise error. In tools that change production systems, a typo such as -Enviroment prod must stop the command, not run it with defaults.
How: the anatomy
function Get-Data {
[CmdletBinding()] # attribute on the param block
param([string]$Env = 'dev')
Write-Verbose "Loading inventory for $Env" # shown only with -Verbose
Write-Debug "raw env value: [$Env]" # shown only with -Debug
$n = (Import-Csv ~/pslab/data/servers.csv | Where-Object Env -eq $Env).Count
Write-Verbose "Found $n servers"
$n # output
}
-Verbose sets $VerbosePreference = 'Continue' inside the function; because preference variables are ordinary variables read through the scope chain, every function and cmdlet called from there also becomes verbose. -Debug in PowerShell 7 sets $DebugPreference = 'Continue' (Windows PowerShell 5.1 used Inquire and prompted on every message).
When: $PSBoundParameters vs the variable
$Port always has a value (the default if not passed). $PSBoundParameters is a dictionary of only the parameters the caller actually bound (including common parameters such as Verbose=True). Use $PSBoundParameters.ContainsKey('Port') when “not given” and “given the default value” must behave differently — Get-OpsConfig uses this to fall back to DefaultEnv from the config file. Module 7 uses the same dictionary for forwarding (@PSBoundParameters).
[CmdletBinding()] is only needed for -Verbose” — its main value is strict binding and the cmdlet API. ② “Defaults appear in $PSBoundParameters” — they do not. ③ “Write-Verbose output is part of the result” — it is stream 4, never captured by $x = f. ④ “-Debug prompts” — only in Windows PowerShell 5.1. ⑤ “A function needs [CmdletBinding()] to use [Parameter(Mandatory)]” — any [Parameter()] already makes it advanced; write [CmdletBinding()] anyway for clarity.Diagram: what [CmdletBinding()] adds
Diagram: preference propagation
Simple vs advanced: the same call, two outcomes
Pick a call and step through binding for a simple function (no attributes) and its advanced twin. Outcomes reproduced on 7.6.10.
Command reference
| Syntax | Purpose | Notes |
|---|---|---|
[CmdletBinding()] param(…) | Make the function advanced | Options: DefaultParameterSetName, SupportsShouldProcess (Lesson 5), PositionalBinding |
Write-Verbose "…" / -Verbose | Optional diagnostics | Stream 4 |
Write-Debug "…" / -Debug | Developer detail | Stream 5; no prompt in 7.x |
Write-Error "…" | Non-terminating error that honours -ErrorAction | Lesson 5 for details |
$PSCmdlet.ThrowTerminatingError($record) | Stop with a proper ErrorRecord | Error points at the caller's line, not inside your function |
$PSCmdlet.ParameterSetName | Which set was chosen | Module 4 |
$PSBoundParameters.ContainsKey('X') | Was -X passed? | Defaults are not included |
(Get-Command f).CmdletBinding | Is f advanced? | True/False |
function Get-Simple { param([string]$Name) "Hello $Name; args=[$($args -join ',')]" }
function Get-Advanced { [CmdletBinding()] param([string]$Name) "Hello $Name" }
Get-Simple -Nmae ops
Get-Advanced -Nmae ops
Get-Simple ops extra1 extra2
Get-Advanced ops extra1
Hello ; args=[-Nmae,ops] Get-Advanced: A parameter cannot be found that matches parameter name 'Nmae'. Hello ops; args=[extra1,extra2] Get-Advanced: A positional parameter cannot be found that accepts argument 'extra1'.
(Get-Command Get-Simple).Parameters.Keys -join ', ' (Get-Command Get-Advanced).Parameters.Keys -join ', '
Name Name, Verbose, Debug, ErrorAction, WarningAction, InformationAction, ProgressAction, ErrorVariable, WarningVariable, InformationVariable, OutVariable, OutBuffer, PipelineVariable
How to verify: ProgressAction is in the list — it was added in 7.4, so scripts that splat common parameters to Windows PowerShell 5.1 commands can trip over it. Common mistake: defining your own -Verbose or -ErrorAction parameter (error: a parameter with that name was defined multiple times). Production use: make every function in a module advanced; PSScriptAnalyzer (Lesson 8) flags missing [CmdletBinding()].
Get-Data -Env prod
Get-Data -Env prod -Verbose
Get-Data -Env prod -Debug
function Invoke-Outer { [CmdletBinding()] param() Write-Verbose 'outer'; Get-Data -Env dev }
Invoke-Outer -Verbose
6 VERBOSE: Loading inventory for prod VERBOSE: Found 6 servers 6 DEBUG: raw env value: [prod] 6 VERBOSE: outer VERBOSE: Loading inventory for dev VERBOSE: Found 3 servers 3
function Show-Invocation {
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param(
[Parameter(ParameterSetName = 'ByName', Position = 0)] [string]$Name,
[Parameter(ParameterSetName = 'ById')] [int]$Id,
[int]$Port = 8080
)
"ParameterSetName : $($PSCmdlet.ParameterSetName)"
"Command : $($PSCmdlet.MyInvocation.MyCommand.Name)"
"Line : $($PSCmdlet.MyInvocation.Line.Trim())"
"BoundParameters : $(($PSBoundParameters.GetEnumerator() | ForEach-Object { '{0}={1}' -f $_.Key, $_.Value }) -join '; ')"
"Port was passed? : $($PSBoundParameters.ContainsKey('Port')) (value $Port)"
}
Show-Invocation web-01
Show-Invocation -Id 7 -Port 443 -Verbose
ParameterSetName : ByName Command : Show-Invocation Line : Show-Invocation web-01 BoundParameters : Name=web-01 Port was passed? : False (value 8080) ParameterSetName : ById Command : Show-Invocation Line : Show-Invocation -Id 7 -Port 443 -Verbose BoundParameters : Id=7; Port=443; Verbose=True Port was passed? : True (value 443)
Goal: Upgrade a simple function, prove what changes, and use the cmdlet API. Environment: pwsh 7.6, ~/pslab. Cost: none.
function New-Check {
[CmdletBinding()]
param([string]$Name, $Expected, $Actual)
"$Name expected=$Expected actual=$Actual"
}
New-Check 'envs' 'a,b' ('b', 'a' | Sort-Object) -join ','
New-Check 'envs' 'a,b' (('b', 'a' | Sort-Object) -join ',')
New-Check: A parameter cannot be found that matches parameter name 'join'. envs expected=a,b actual=a,b
Get-Data from the Principles tab and run it with and without -Verbose and -Debug (outputs in the Commands tab). Then capture: $n = Get-Data -Env prod -Verbose — the VERBOSE lines appear on screen, $n is just 6.-ErrorAction works on your function:
function Get-Thing {
[CmdletBinding()]
param([string]$Name)
if ($Name -eq 'bad') { Write-Error "Get-Thing: cannot find '$Name'"; return }
"thing $Name"
}
Get-Thing bad -ErrorAction SilentlyContinue; 'continued after SilentlyContinue'
try { Get-Thing bad -ErrorAction Stop } catch { "caught: $($_.Exception.Message)" }
Get-Thing bad -ErrorVariable ev -ErrorAction SilentlyContinue; "ErrorVariable holds: $ev"
continued after SilentlyContinue caught: Get-Thing: cannot find 'bad' ErrorVariable holds: Get-Thing: cannot find 'bad'
function Get-Strict {
[CmdletBinding()]
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
$err = [System.Management.Automation.ErrorRecord]::new(
[System.IO.FileNotFoundException]::new("Inventory not found: $Path"),
'OpsKit.InventoryNotFound', 'ObjectNotFound', $Path)
$PSCmdlet.ThrowTerminatingError($err)
}
'found'
}
Get-Strict ./nope.json
$Error[0].FullyQualifiedErrorId
$Error[0].CategoryInfo.Category
Get-Strict: Inventory not found: ./nope.json OpsKit.InventoryNotFound,Get-Strict ObjectNotFound
function Get-Pos { [CmdletBinding()] param([string]$A, [string]$B) "A=$A B=$B" }
function Get-NoPos { [CmdletBinding(PositionalBinding = $false)] param([string]$A, [string]$B) "A=$A B=$B" }
Get-Pos one two
Get-NoPos one two
A=one B=two Get-NoPos: A positional parameter cannot be found that accepts argument 'one'.
Case 1: a typo that reset a production pool
Problem: Reset-AppPool -Enviroment prod (typo) recycled the dev pool — the default — and the on-call engineer thought prod was fixed. Root cause: a simple function; the misspelled parameter went into $args. Fix: [CmdletBinding()] plus [ValidateSet()] and no default for the environment (Module 5). Prevention: code review checklists (and PSScriptAnalyzer in CI, Lesson 8) that require advanced functions in shared modules.
Case 2: verbose logs that never appeared in CI
Problem: A module used Write-Host for progress so that “it shows in CI”, which made the output impossible to silence or capture. Fix: Write-Verbose everywhere; the pipeline step calls the entry script with -Verbose when debugging is needed. Preference propagation makes every inner function verbose automatically.
Case 3: -ErrorAction Stop ignored by a wrapper
Problem: try { Sync-Inventory -ErrorAction Stop } catch { … } never caught anything. Root cause: Sync-Inventory was a simple function: it had no common parameters, and its Write-Error calls used the caller's (Continue) preference. In 7.6 passing -ErrorAction to it just landed in $args. Fix: make it advanced so -ErrorAction Stop sets $ErrorActionPreference inside it.
Common errors and fixes
A parameter cannot be found that matches parameter name 'X'.
Cause: typo, wrong parameter set, or an operator such as -join/-split in argument mode (wrap the expression in parentheses).
Get-Command MyFunc -Syntax
A positional parameter cannot be found that accepts argument 'x'.
Cause: more positional arguments than positional parameters; often a missing comma in an array (-Tag web api instead of -Tag web, api) or PositionalBinding = $false.
A parameter with the name 'Verbose' was defined multiple times for the command.
Cause: you declared a common parameter yourself in an advanced function.
Fix: remove it; use $PSBoundParameters['Verbose'] or $VerbosePreference if you need to know.
Write-Verbose prints nothing
Cause: the function is simple (no -Verbose parameter), or $VerbosePreference was set to SilentlyContinue inside.
Fix: add [CmdletBinding()]; check (Get-Command f).CmdletBinding.
1. List all advanced functions currently defined in your session.
Get-Command -CommandType Function | Where-Object CmdletBinding | Select-Object Name, Source
2. Write Get-Port that warns (verbose) when -Port was not passed and the default 8080 is used.
function Get-Port {
[CmdletBinding()]
param([int]$Port = 8080)
if (-not $PSBoundParameters.ContainsKey('Port')) { Write-Verbose "No -Port given; using $Port" }
$Port
}
Get-Port -VerboseYour team wants to convert 200 simple functions to advanced ones. What can break?
Callers that relied on $args or passed extra/misspelled arguments now fail (that is the point — fix them). Functions that declared their own $Verbose/$Debug parameters fail to load. Positional calls may bind differently because every parameter now gets a position in declaration order unless PositionalBinding = $false. Functions that read $input instead of declaring pipeline parameters need a pipeline parameter and a process block (Module 6). Roll out with tests.
Verified teaching videos
Official documentation
- about_Functions_Advanced · about_Functions_CmdletBindingAttribute · about_Functions_Advanced_Methods ($PSCmdlet) · about_CommonParameters
Video storyboard (about 90 seconds)
Visual: the call “-Nmae ops” enters two doors; the simple-function door lets it slip into a bag labelled $args, the advanced door rejects it.
Narration: one attribute turns silent typos into errors.
Visual: a -Verbose switch flips a lamp on in the function and in every room it calls.
Narration: common parameters come free, and preferences flow down the call chain.
Visual: a clipboard titled $PSBoundParameters listing only what the caller wrote.
Narration: PSBoundParameters tells you what was really passed.
Module 4 · Parameters: types, Mandatory, Position, switches and parameter sets
Mandatory and Position shape the syntax diagram, [switch] expresses yes/no, and parameter sets describe which combinations are legal- Choose parameter types and predict conversion (
'8080'→ 8080,8080.6→ 8081,'abc'→ error;[bool]refuses strings). - Use
[Parameter(Mandatory)],HelpMessage,[AllowEmptyString()], and know how mandatory parameters behave interactively and with-NonInteractive. - Set Position and default values (including expressions that use earlier parameters), and use
[switch]correctly (-Force:$false, never default to$true). - Design parameter sets with
DefaultParameterSetName, read the resulting syntax diagram, branch on$PSCmdlet.ParameterSetName, and add aliases.
What: the parts of a parameter declaration
[Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', HelpMessage = '…')]
[Alias('Address')] # extra names (also used for pipeline ByPropertyName, Module 6)
[ValidateSet('dev', 'prod')] # validation (Module 5)
[string[]] # type: conversion happens BEFORE validation
$Name = 'default' # default (ignored when Mandatory)
Why: types do the parsing for you
| Type | Input | Result (7.6.10) |
|---|---|---|
[int] | '8080' | 8080 (Int32) |
[int] | 8080.6 | 8081 — rounded, no error |
[int] | abc | Cannot process argument transformation on parameter 'Port'. Cannot convert value "abc" to type "System.Int32". |
[string[]] | web / web, api | Array of 1 / 2 — one parameter accepts both |
[ipaddress] | 10.30.1.999 | … Error: "An invalid IP address was specified." |
[bool] | 'false' | Error: Boolean parameters accept only Boolean values and numbers — use [switch] |
How: Mandatory, Position, defaults, switches
- Mandatory: if missing, an interactive host prompts (Supply values for the following parameters); with
-NonInteractivethe call fails. A mandatory[string]also rejects''and$nullunless you add[AllowEmptyString()]/[AllowNull()]. - Position: lets callers omit the name. In advanced functions, parameters without an explicit
Positionare positional in declaration order unless any parameter declares a Position — then only those are. Give positions only to the one or two obvious arguments. - Defaults are evaluated at call time, in declaration order, so a later default can use an earlier parameter (
$Scheme = $(if ($Port -eq 443) {'https'} else {'http'})). [switch]: present =$true.-Force:$falseand-Force:$varpass a value explicitly (needed when forwarding). Never give a switch a default of$true: the caller could only turn it off with the odd-Switch:$false.
When: parameter sets
Use parameter sets when there are mutually exclusive ways to identify the target (by name, by environment, by IP). Each parameter belongs to one or more sets; parameters without ParameterSetName belong to all. The binder picks the set that matches the parameters supplied. If several sets are still possible, DefaultParameterSetName decides; without it, you get “Parameter set cannot be resolved using the specified named parameters”.
[int] rejects decimals” — it rounds them. ② “A [bool] parameter is the same as a switch” — it requires a value and rejects 'false'. ③ “Mandatory parameters fail fast” — interactively they prompt and can hang an automation run without -NonInteractive. ④ “Parameters in no set are in no set” — they are in all sets (__AllParameterSets). ⑤ “Defaults are applied to Mandatory parameters” — never; and validation does not run on defaults (Module 5).Diagram: Get-Node's three parameter sets
Diagram: how the binder resolves a set
Parameter-set resolver
Pick a call to Get-Node (definition in the Commands tab) and watch the binder narrow the candidate sets. Outcomes reproduced on 7.6.10.
Command reference
| Syntax | Purpose | Notes |
|---|---|---|
[Parameter(Mandatory)] | Required | Prompts interactively; HelpMessage shown after !? |
[Parameter(Position = 0)] | Name optional | Shown as [-Name] in the syntax |
[Parameter(ParameterSetName = 'X')] | Member of a set | Repeat the attribute for several sets |
[CmdletBinding(DefaultParameterSetName = 'X')] | Tie-breaker | Required as soon as you have sets |
[switch]$Force | On/off flag | -Force:$false to pass explicitly |
[Alias('CN')] | Alternative name | Also binds ByPropertyName |
[AllowEmptyString()], [AllowNull()], [AllowEmptyCollection()] | Relax Mandatory checks | For “present but empty” values |
Get-Command f -Syntax | Show the resulting syntax | One line per set |
function Test-Port {
[CmdletBinding()]
param([int]$Port, [string[]]$Tag)
"Port=$Port ($($Port.GetType().Name)) Tags=$($Tag.Count)"
}
Test-Port -Port '8080' -Tag web
Test-Port -Port 8080.6 -Tag web, api
Test-Port -Port abc
function Test-Flag { [CmdletBinding()] param([bool]$Enabled) "Enabled=$Enabled" }
Test-Flag -Enabled 'false'
Port=8080 (Int32) Tags=1 Port=8081 (Int32) Tags=2 Test-Port: Cannot process argument transformation on parameter 'Port'. Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format." Test-Flag: Cannot process argument transformation on parameter 'Enabled'. Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
function Get-Server {
[CmdletBinding()]
param(
[Parameter(Mandatory, HelpMessage = 'Environment: dev, staging or prod')]
[string]$Env
)
"env=$Env"
}
Get-Server -Env ''
pwsh -NoProfile -NonInteractive -Command 'function Get-Server { [CmdletBinding()] param([Parameter(Mandatory)][string]$Env) "env=$Env" }; Get-Server'
"exit code: $LASTEXITCODE"
Get-Server: Cannot bind argument to parameter 'Env' because it is an empty string. Get-Server: Cannot process command because of one or more missing mandatory parameters: Env. exit code: 1
How to verify: in an interactive console, Get-Server without -Env shows a prompt; type !? to see the HelpMessage. Common mistake: mandatory parameters in scripts run by schedulers without -NonInteractive — the job hangs at the prompt. Production use: make environment/target parameters mandatory and give everything else safe defaults.
function Get-Node {
[CmdletBinding(DefaultParameterSetName = 'ByEnv')]
param(
[Parameter(ParameterSetName = 'ByName', Mandatory, Position = 0)]
[string]$Name,
[Parameter(ParameterSetName = 'ByEnv')]
[string]$Env = 'dev',
[Parameter(ParameterSetName = 'ByIP', Mandatory)]
[Alias('Address')]
[ipaddress]$IP,
[int]$Port = 8080
)
"set=$($PSCmdlet.ParameterSetName) " + $(switch ($PSCmdlet.ParameterSetName) {
'ByName' { "name=$Name" } 'ByEnv' { "env=$Env" } 'ByIP' { "ip=$IP" } })
}
Get-Command Get-Node -Syntax
Get-Node
Get-Node web-01
Get-Node -Env prod -Port 443
Get-Node -Address 10.30.1.41
Get-Node -Name web-01 -Env prod
Get-Node -IP 10.30.1.999
Get-Node [-Env <string>] [-Port <int>] [<CommonParameters>] Get-Node [-Name] <string> [-Port <int>] [<CommonParameters>] Get-Node -IP <ipaddress> [-Port <int>] [<CommonParameters>] set=ByEnv env=dev set=ByName name=web-01 set=ByEnv env=prod set=ByIP ip=10.30.1.41 Get-Node: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided. Get-Node: Cannot process argument transformation on parameter 'IP'. Cannot convert value "10.30.1.999" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
(Get-Command Get-Node).Parameters.Values |
Where-Object Name -in 'Name', 'Env', 'IP', 'Port' |
Format-Table Name, ParameterType, @{ n = 'Sets'; e = { $_.ParameterSets.Keys -join ',' } }, Aliases -AutoSize
Name ParameterType Sets Aliases
---- ------------- ---- -------
Name System.String ByName {}
Env System.String ByEnv {}
IP System.Net.IPAddress ByIP {Address}
Port System.Int32 __AllParameterSets {}
Goal: Build Get-Node with three parameter sets, then explore defaults and switches. Environment: pwsh 7.6. Cost: none.
Get-Node from the Commands tab, run the seven calls, and compare with the syntax diagram. Then remove DefaultParameterSetName and run Get-Node with no arguments — explain the error.function Get-Node2 {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = 'ByName')] [string]$Name,
[Parameter(ParameterSetName = 'ByEnv')] [string]$Env
)
"set=$($PSCmdlet.ParameterSetName)"
}
Get-Node2
Get-Node2 -Name a
Get-Node2: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided. set=ByName
function New-Url {
[CmdletBinding()]
param(
[string]$HostName = 'localhost',
[int]$Port = 8080,
[string]$Scheme = $(if ($Port -eq 443) { 'https' } else { 'http' })
)
"{0}://{1}:{2}" -f $Scheme, $HostName, $Port
}
New-Url
New-Url -Port 443 -HostName shop.example.com
http://localhost:8080 https://shop.example.com:443
function Remove-Cache {
[CmdletBinding()]
param([switch]$Force)
"Force.IsPresent=$($Force.IsPresent) if(`$Force)=$(if ($Force) { 'yes' } else { 'no' }) type=$($Force.GetType().Name)"
}
Remove-Cache
Remove-Cache -Force
Remove-Cache -Force:$false
$wantForce = $true; Remove-Cache -Force:$wantForce
Force.IsPresent=False if($Force)=no type=SwitchParameter Force.IsPresent=True if($Force)=yes type=SwitchParameter Force.IsPresent=False if($Force)=no type=SwitchParameter Force.IsPresent=True if($Force)=yes type=SwitchParameter
function Set-Note {
[CmdletBinding()]
param([Parameter(Mandatory)] [AllowEmptyString()] [string]$Text)
"note=[$Text]"
}
Set-Note -Text ''
note=[]
Get-Node -Addr 10.30.1.41 works (unique prefix of the alias Address) and prints set=ByIP ip=10.30.1.41. Abbreviations are fine at the prompt; in scripts, always spell out the name (Lesson 1 Module 3).Case 1: a nightly job that “hung” for three days
Problem: After a refactor added [Parameter(Mandatory)] $Region to a cleanup script, the scheduled task never finished. Root cause: the task ran pwsh -File cleanup.ps1 without -Region and without -NonInteractive; PowerShell waited at the prompt in an invisible session. Fix: pass the value, and always schedule with -NoProfile -NonInteractive, which turns the prompt into an immediate error (exit code 1).
Case 2: -Recurse $true did nothing
Problem: A wrapper declared [bool]$Recurse = $true and callers wrote -Recurse (no value) — error — or -Recurse 0. Fix: [switch]$Recurse and forward it as -Recurse:$Recurse. A switch whose default is $true is a design smell: rename it (-NoRecurse).
Case 3: two ways to identify a VM, both given
Problem: Stop-LabVm -Name web-01 -Id 42 stopped VM 42, which was not web-01; the function silently preferred $Id. Fix: put -Name and -Id in different parameter sets; the binder now rejects the ambiguous call before anything is stopped.
Common errors and fixes
Parameter set cannot be resolved using the specified named parameters.
Cause: parameters from two sets were combined, or several sets match and there is no DefaultParameterSetName.
Get-Command f -Syntax (Get-Command f).ParameterSets | Select-Object Name, IsDefault
Cannot process argument transformation on parameter 'X'. Cannot convert value …
Cause: the argument cannot be converted to the declared type (also happens for arrays passed to scalar parameters).
Fix: pass the right type, or widen the type ([string[]]) deliberately.
Cannot bind argument to parameter 'X' because it is an empty string / is null.
Cause: Mandatory parameters reject empty values.
Fix: fix the caller, or add [AllowEmptyString()] / [AllowNull()] if empty is legitimate.
Cannot process command because of one or more missing mandatory parameters: X.
Cause: -NonInteractive session and a mandatory parameter was not supplied (or a pipeline object lacked it, Module 6).
1. Show which parameter set is the default for Get-ChildItem and for your Get-Node.
(Get-Command Get-ChildItem).ParameterSets | Select-Object Name, IsDefault (Get-Command Get-Node).DefaultParameterSet
2. Add a -Tag parameter that is mandatory only in the ByEnv set.
[Parameter(ParameterSetName = 'ByEnv', Mandatory)] [Parameter(ParameterSetName = 'ByName')] [string[]]$Tag
Repeat the [Parameter()] attribute once per set; each copy can have different Mandatory/Position values.
Design the parameters of Get-OpsConfig: it returns one environment's settings, or the whole configuration. Why use a switch in its own set rather than -Env all?
The two modes return different types (an OpsKit.EnvConfig object vs a hashtable) — a strong signal for two parameter sets, each with its own [OutputType] (Module 7). A magic value like 'all' would have to be allowed by ValidateSet, would show up in tab completion as an environment, and would need special-casing everywhere. With sets, Get-OpsConfig -Env prod -All is rejected by the binder for free (Module 8 shows the real error).
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
Visual: a form with typed fields; '8080' slides into an Int box, 'abc' bounces off.
Narration: the parameter type converts or rejects input before your code runs.
Visual: three doors labelled ByName, ByEnv, ByIP; a call with two keys is turned away.
Narration: parameter sets describe the legal combinations.
Visual: a light switch labelled -Force.
Narration: yes/no options are switches — never booleans with a default of true.
Module 5 · Validation and completion: Validate* attributes and argument completers
- Choose the right attribute:
ValidateSet,ValidatePattern,ValidateRange(including'Positive'),ValidateScript,ValidateNotNullOrEmpty,ValidateNotNullOrWhiteSpace,ValidateCount,ValidateLength. - Recognise each attribute's error message, and replace unreadable ones with
ErrorMessage = '… {0} …'. - Know the edges: validation runs after type conversion, not on default values, but again on every later assignment to the parameter variable.
- Add completion with
ValidateSet(free),[ArgumentCompleter()],[ArgumentCompletions()]andRegister-ArgumentCompleter, and test completers without a keyboard usingTabExpansion2.
What: validation attributes
| Attribute | Checks | Error starts with (7.6.10) |
|---|---|---|
[ValidateSet('dev','staging','prod')] | One of a fixed list; case-insensitive by default (IgnoreCase = $false to change); also gives tab completion | The argument "qa" does not belong to the set "dev,staging,prod" … |
[ValidatePattern('^[a-z]+-\d{2}$')] | Regex match (case-insensitive) | The argument "Web_3" does not match the "^[a-z]+-\d{2}$" pattern … |
[ValidateRange(1, 60)], [ValidateRange('Positive')] | Numeric range; kinds Positive, NonNegative, Negative, NonPositive | The 0 argument is less than the minimum allowed range of 1 … |
[ValidateScript({ Test-Path $_ })] | Any condition; must return $true | The " Test-Path -LiteralPath $_ " validation script … did not return a result of True |
[ValidateNotNullOrEmpty()] | Not $null, '' or an empty collection | The argument is null or empty … |
[ValidateNotNullOrWhiteSpace()] (7.4+) | Also rejects ' ' | … consists of only white-space characters … |
[ValidateCount(1, 3)], [ValidateLength(1, 10)] | Number of elements / string length | The parameter requires at least 1 value(s) and no more than 3 … |
Why: reject bad input before any side effect
Validation runs in the binder, before begin/process. A tool that restarts services or deletes backups should never start work with -Env qa or -Keep 0. It also documents intent: Get-Help and the syntax diagram show the attributes' effect, and ValidateSet values appear in tab completion.
How: custom messages
ValidatePattern and ValidateScript accept ErrorMessage, where {0} is the value (and {1} the pattern or script). Compare “The " Test-Path -LiteralPath $_ " validation script for the argument with value "./nope.json" did not return a result of True” with “File not found: ./nope.json”. Inside ValidateScript you can also throw "…" to produce your own message.
When: completion without restriction
| Mechanism | Restricts values? | Use for |
|---|---|---|
ValidateSet | Yes | Fixed, small lists (environments) |
[ArgumentCompletions('a','b')] | No | Common suggestions, other values allowed |
[ArgumentCompleter({ … })] | No | Dynamic suggestions computed at completion time (regions from the inventory) |
Register-ArgumentCompleter | No | Add completion to someone else's command, or from a profile/module without editing the function |
[ValidateRange(1,10)][int]$N = 99 happily runs with 99. ② “Validation only happens once” — assigning to the parameter variable later re-validates (The variable cannot be validated because the value 12 is not a valid value for the Limit variable). ③ “ValidateSet is case-sensitive” — it is not by default, and the value keeps the caller's casing (PROD). ④ “A completer validates” — completers only suggest; -Region eastus still binds. ⑤ “ValidateScript can use other parameters” — not reliably: they may not be bound yet; cross-parameter checks belong in the body.Diagram: where validation sits in binding
Diagram: how tab completion asks your code
Validation gate: which attribute stops this value?
Choose an argument and step through conversion and each validation attribute. Messages are real 7.6.10 output.
Command reference
| Syntax | Purpose | Notes |
|---|---|---|
[ValidateSet('a','b')] | Fixed list + completion | IgnoreCase = $false for exact case |
[ValidatePattern('re', ErrorMessage = '…{0}…')] | Regex | Anchor with ^…$ |
[ValidateRange(1, 65535)] | Numeric range | Or a kind: 'Positive' |
[ValidateScript({ … }, ErrorMessage = '…')] | Any rule | $_ is the value |
[ValidateNotNullOrEmpty()] / [ValidateNotNullOrWhiteSpace()] | Non-empty | The second needs 7.4+ |
[ArgumentCompleter({ param($c,$p,$w,$a,$f) … })] | Dynamic completion | Return strings or CompletionResult |
Register-ArgumentCompleter -CommandName C -ParameterName P -ScriptBlock { … } | Completion from outside | Session-wide; put it in a module or profile |
TabExpansion2 -inputScript 'cmd -P ' -cursorColumn N | Test completion in scripts | .CompletionMatches |
function Get-Srv {
[CmdletBinding()]
param(
[ValidateSet('dev', 'staging', 'prod')] [string]$Env = 'dev',
[ValidateSet('web', 'api', 'db', IgnoreCase = $false)] [string]$Role = 'web'
)
"env=$Env role=$Role"
}
Get-Srv -Env PROD
Get-Srv -Env qa
Get-Srv -Role WEB
env=PROD role=web Get-Srv: Cannot validate argument on parameter 'Env'. The argument "qa" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. Get-Srv: Cannot validate argument on parameter 'Role'. The argument "WEB" does not belong to the set "web,api,db" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
function New-ServerName {
[CmdletBinding()]
param(
[ValidatePattern('^[a-z]+-\d{2}$', ErrorMessage = "'{0}' is not a valid server name (expected e.g. web-03)")]
[string]$Name
)
"ok: $Name"
}
New-ServerName web-03
New-ServerName Web_3
function New-ServerName2 { [CmdletBinding()] param([ValidatePattern('^[a-z]+-\d{2}$')] [string]$Name) "ok: $Name" }
New-ServerName2 Web_3
ok: web-03
New-ServerName: Cannot validate argument on parameter 'Name'. 'Web_3' is not a valid server name (expected e.g. web-03)
New-ServerName2: Cannot validate argument on parameter 'Name'. The argument "Web_3" does not match the "^[a-z]+-\d{2}$" pattern. Supply an argument that matches "^[a-z]+-\d{2}$" and try the command again.
function Set-Timeout {
[CmdletBinding()]
param(
[ValidateRange(1, 60)] [int]$Seconds = 5,
[ValidateRange('Positive')] [int]$Retries = 3
)
"timeout=$Seconds retries=$Retries"
}
Set-Timeout -Seconds 0
Set-Timeout -Retries 0
Set-Timeout -Seconds 30 -Retries 2
Set-Timeout: Cannot validate argument on parameter 'Seconds'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again. Set-Timeout: Cannot validate argument on parameter 'Retries'. The argument "0" cannot be validated because its value is not greater than zero. timeout=30 retries=2
function Import-Inventory {
[CmdletBinding()]
param(
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf }, ErrorMessage = 'File not found: {0}')]
[string]$Path
)
"importing $Path"
}
Import-Inventory -Path ~/pslab/data/inventory.json
Import-Inventory -Path ~/pslab/data/nope.json
importing ~/pslab/data/inventory.json Import-Inventory: Cannot validate argument on parameter 'Path'. File not found: ~/pslab/data/nope.json
function Send-Report {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()] [string]$To,
[ValidateNotNullOrWhiteSpace()] [string]$Subject = 'report',
[ValidateCount(1, 3)] [string[]]$Cc = @('ops@example.com'),
[ValidateLength(1, 10)] [string]$Tag = 'daily'
)
"to=$To subject=$Subject cc=$($Cc.Count) tag=$Tag"
}
Send-Report -To ''
Send-Report -To a@example.com -Subject ' '
Send-Report -To a@example.com -Cc a, b, c, d
Send-Report -To a@example.com -Tag 'much-too-long'
Send-Report -To a@example.com
Send-Report: Cannot validate argument on parameter 'To'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. Send-Report: Cannot validate argument on parameter 'Subject'. The argument is null, empty, or consists of only white-space characters. Provide an argument that contains non white-space characters, and then try the command again. Send-Report: Cannot validate argument on parameter 'Cc'. The parameter requires at least 1 value(s) and no more than 3 value(s) - 4 value(s) were provided. Send-Report: Cannot validate argument on parameter 'Tag'. The character length of the 13 argument is too long. Shorten the character length of the argument so it is fewer than or equal to "10" characters, and then try the command again. to=a@example.com subject=report cc=1 tag=daily
How to verify: every message begins with Cannot validate argument on parameter 'X' and the error ID is ParameterArgumentValidationError ($Error[0].FullyQualifiedErrorId). Common mistake: an unanchored pattern such as '[a-z]+-\d{2}' also accepts xx web-01 yy. Production use: validate environment names, ports, counts and paths in every function that changes something.
Goal: Probe the edges of validation and build three kinds of completion, tested with TabExpansion2. Environment: pwsh 7.6, OpsKit loaded (. ~/pslab/OpsKit/OpsKit.ps1 after Module 8, or use the inventory directly). Cost: none.
function Get-Default { [CmdletBinding()] param([ValidateRange(1, 10)] [int]$N = 99) "N=$N" }
Get-Default
function Set-Limit {
[CmdletBinding()]
param([ValidateRange(1, 10)] [int]$Limit = 5)
$Limit = $Limit * 3
"limit=$Limit"
}
Set-Limit -Limit 2
Set-Limit -Limit 4
N=99 limit=6 Set-Limit: The variable cannot be validated because the value 12 is not a valid value for the Limit variable.
Lesson learned: do not reuse a validated parameter variable for intermediate values; use a new variable ($effective = $Limit * 3).
(TabExpansion2 -inputScript 'Get-OpsServer -Env ' -cursorColumn 19).CompletionMatches.CompletionText -join ' ' (TabExpansion2 -inputScript 'Get-OpsServer -Env p' -cursorColumn 20).CompletionMatches.CompletionText -join ' '
dev prod staging prod
function Get-OpsRegion {
[CmdletBinding()]
param(
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
(Get-OpsServer).Region | Sort-Object -Unique | Where-Object { $_ -like "$wordToComplete*" }
})]
[string]$Region
)
Get-OpsServer | Where-Object Region -eq $Region | Select-Object -ExpandProperty Name
}
(TabExpansion2 -inputScript 'Get-OpsRegion -Region ' -cursorColumn 22).CompletionMatches.CompletionText -join ' '
(TabExpansion2 -inputScript 'Get-OpsRegion -Region ca-' -cursorColumn 25).CompletionMatches.CompletionText -join ' '
Get-OpsRegion -Region eastus
ca-central-1 canadacentral ca-central-1
The last call returns nothing and raises no error: a completer suggests, it does not validate.
function Get-Log { [CmdletBinding()] param([ArgumentCompletions('access.log', 'error.log')] [string]$File) "file=$File" }
(TabExpansion2 -inputScript 'Get-Log -File ' -cursorColumn 14).CompletionMatches.CompletionText -join ' '
Get-Log -File other.log
access.log error.log file=other.log
Register-ArgumentCompleter -CommandName Test-OpsEndpoint -ParameterName Target -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
Get-OpsServer | Where-Object IP -like "$wordToComplete*" | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.IP, $_.IP, 'ParameterValue', "$($_.Name) ($($_.Env))")
}
}
(TabExpansion2 -inputScript 'Test-OpsEndpoint -Target 10.30.1.' -cursorColumn 33).CompletionMatches |
Format-Table CompletionText, ToolTip -AutoSize
Register-ArgumentCompleter -CommandName Get-OpsServer -ParameterName Name -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
$p = @{}; if ($fakeBoundParameters.ContainsKey('Env')) { $p.Env = $fakeBoundParameters.Env }
Get-OpsServer @p | Select-Object -ExpandProperty Name -Unique | Where-Object { $_ -like "$wordToComplete*" }
}
(TabExpansion2 -inputScript 'Get-OpsServer -Env prod -Name ' -cursorColumn 30).CompletionMatches.CompletionText -join ' '
(TabExpansion2 -inputScript 'Get-OpsServer -Env dev -Name ' -cursorColumn 29).CompletionMatches.CompletionText -join ' '
CompletionText ToolTip -------------- ------- 10.30.1.41 web-01 (prod) 10.30.1.42 web-02 (prod) 10.30.1.43 api-01 (prod) 10.30.1.44 db-01 (prod) web-01 web-02 api-01 edge-01 db-01 bastion-01 web-01 api-01 db-01
Case 1: a backup rotation that deleted every backup
Problem: Remove-OldBackup -Keep $cfg.Keep deleted all backups after someone emptied Keep in the config: $null converted to [int] 0, “keep the newest 0”. Root cause: no validation. Fix: [ValidateRange(1, 365)][int]$Keep — the call now fails before any deletion. Lesson 5's Invoke-OpsBackup carries this validation plus -WhatIf.
Case 2: an unreadable error that cost an hour
Problem: Operators kept reporting “The " $_ -match '^(?=.{3,15}$)[a-z][a-z0-9-]*$' " validation script … did not return a result of True” for VM names. Fix: ErrorMessage = "VM name '{0}' must be 3-15 chars, lowercase letters, digits and dashes". Validation messages are user interface.
Case 3: a completer that froze the console
Problem: A completer called a cloud API on every Tab press; with a slow network the console froze for seconds. Fix: cache results in a $script: variable with a timestamp (Module 2), keep completers local and fast, and never make them change state.
Common errors and fixes
Cannot validate argument on parameter 'X'. …
Cause: the value failed a Validate* attribute. The rest of the message tells you which one.
(Get-Command f).Parameters['X'].Attributes | Select-Object TypeId
The variable cannot be validated because the value … is not a valid value for the X variable.
Cause: the body assigned a new value to a validated parameter variable.
Fix: use a separate variable.
Tab completion shows file names instead of my values
Cause: the completer threw or returned nothing, so PowerShell fell back to path completion; or Register-ArgumentCompleter used the wrong command/parameter name.
Fix: run the completer through TabExpansion2 and look at $Error[0].
1. Add a port parameter that accepts 1–65535 and is completed with 80, 443 and 8080.
[ArgumentCompletions(80, 443, 8080)] [ValidateRange(1, 65535)] [int]$Port = 8080
2. Print the error ID of a failed validation.
try { Get-OpsServer -Env qa -ErrorAction Stop } catch { $_.FullyQualifiedErrorId }
# ParameterArgumentValidationError,Get-OpsServerShould Get-OpsServer -Env use ValidateSet or a completer that reads the environments from opskit.config.psd1?
Trade-off. ValidateSet gives validation and completion in one line, but the list is hard-coded and must change with the config. A completer reads the real list but does not validate, so you would need a ValidateScript as well (with the same lookup). For v0.1 the three environments are stable, so ValidateSet wins; a large or frequently changing list (regions, subscriptions) calls for completer + script validation, or a class implementing IValidateSetValuesGenerator.
Verified teaching videos
Official documentation
- about_Functions_Advanced_Parameters (validation attributes) · about_Functions_Argument_Completion · Register-ArgumentCompleter
Video storyboard (about 90 seconds)
Visual: a security gate after the type converter; 'qa' is stopped by the ValidateSet guard with a printed reason.
Narration: validation runs before your code, with a precise message.
Visual: a default value walks around the gate; an assignment inside the body is checked again.
Narration: defaults are trusted; reassignments are not.
Visual: pressing Tab pops suggestions from the inventory.
Narration: completers suggest; validators decide.
Module 6 · Pipeline input: ValueFromPipeline(ByPropertyName) and begin / process / end
process, and give parameters the aliases that real objects carry- Declare pipeline parameters with
ValueFromPipeline(the whole object, by type) andValueFromPipelineByPropertyName(a property with the parameter's name or alias). - Explain begin / process / end and reproduce the classic bug: no
processblock → only the last pipeline object is handled. - Support both
-Target a, band'a','b' | …with[string[]]+foreachinsideprocess. - Use
[Alias('IP', 'ComputerName')]so thatImport-Csv servers.csvrows andGet-OpsServerobjects bind, recognise the coercion trap (@{Name=…}as a host name), and prove binding withTrace-Command.
What: three blocks, two ways to receive objects
function Test-Target {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string]$Target
)
begin { } # once, before the first object (pipeline params NOT bound yet)
process { "Target=[$Target]" } # once per pipeline object (or once if no pipeline input)
end { } # once, after the last object
}
| Attribute | Binds | Example input |
|---|---|---|
ValueFromPipeline | The whole object, if it is (or converts to) the parameter type | '10.30.1.41' | Test-Target |
ValueFromPipelineByPropertyName | The value of a property named like the parameter or one of its aliases | Import-Csv servers.csv | Test-Target (property IP) |
Why: a function without process sees only the last object
A function body without named blocks is an end block. The binder still binds each incoming object to $Item — one after another, overwriting — and only then runs end, which sees the last value. Result: 'web-01','api-01','db-01' | Show-Item prints only got db-01, with no error. In begin, pipeline parameters are not bound yet (empty); in end, they still hold the last object.
How: the binder order applies to your parameters
For each object the binder tries, as in Lesson 1: ByValue without coercion → ByPropertyName without coercion → ByValue with coercion → ByPropertyName with coercion. That has a sharp consequence for a [string] parameter with ValueFromPipeline: any object converts to a string. If no property name or alias matches, a CSV row binds as the text @{Name=web-01; Env=dev; …}. With [Alias('IP')], the ByPropertyName attempt (step 2) wins before coercion (step 3) is ever tried.
| Piped object | Without alias | With [Alias('IP','ComputerName')] |
|---|---|---|
'10.30.1.41' | ByValue → 10.30.1.41 | ByValue → 10.30.1.41 |
CSV row (has IP) | ByValue with coercion → @{Name=web-01; Env=dev; …} ✗ | ByPropertyName IP → 10.10.1.21 ✓ |
[pscustomobject]@{ComputerName='build-07'} | @{ComputerName=build-07} ✗ | build-07 ✓ |
| Object with none of the names | Coerced to @{…} text in both cases — a [string] ByValue parameter accepts anything | |
When: ByValue, ByPropertyName or both?
- ByPropertyName for identifiers that objects carry as properties (
IP,Name,Port,Path) — this is what makes your command compose with others. - ByValue on a
[string]when callers will pipe plain strings; accept that unrelated objects will be coerced. On a specific type ([PSTypeName('OpsKit.Server')], Module 7) ByValue is strict. - Collect in
process, compute inendonly when you truly need all objects (sorting, totals) — that turns your function into a blocking stage, likeSort-Object.
process call. ② “Without process I get all objects” — you get the last one. ③ “$Target is available in begin” — not from the pipeline. ④ “If the property does not match, the call fails” — for a [string] ByValue parameter the object is coerced to text instead. ⑤ “$input is the modern way” — it is the automatic enumerator for simple functions; advanced functions use pipeline parameters.Diagram: a CSV row entering Test-Target
Diagram: begin / process / end over time
Core animation: binding into your own function
Choose what is piped and how the function is written, then step through the binder and the blocks. Green = bound/handled, yellow = tried and skipped, red = wrong result or failure. Every outcome was reproduced on PowerShell 7.6.10; the binding lines come from Trace-Command -Name ParameterBinding.
[string] parameter with both pipeline attributes, the trace shows Parameter [Target] PIPELINE INPUT ValueFromPipeline NO COERCION → BIND arg [@{Name=web-01; …}] to param [Target] SKIPPED, then Parameter [Target] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION → BIND arg [10.10.1.21] to param [Target] SUCCESSFUL. Full trace in the Commands tab.Command reference
| Syntax | Purpose | Notes |
|---|---|---|
[Parameter(ValueFromPipeline)] | Bind the whole object | By type, then with coercion |
[Parameter(ValueFromPipelineByPropertyName)] | Bind a property | Name or alias must match |
[Alias('IP','ComputerName')] | Extra property names that bind | Also usable as parameter names |
begin {} process {} end {} | Lifecycle | Body without blocks = end |
process { foreach ($t in $Target) { … } } | Handle arrays from both sources | With [string[]]$Target |
$input | Enumerator of pipeline input in simple functions | Avoid in advanced functions |
Trace-Command -Name ParameterBinding -PSHost -Expression { … } | Prove the binding | Read the BIND PIPELINE part |
function Show-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
"got $Item" # no process block → this is the end block
}
'web-01', 'api-01', 'db-01' | Show-Item
function Show-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
process { "got $Item" }
}
'web-01', 'api-01', 'db-01' | Show-Item
got db-01 got web-01 got api-01 got db-01
function Measure-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
begin { Write-Host "begin: Item=[$Item]"; $n = 0 }
process { $n++; Write-Host "process: Item=[$Item]" }
end { Write-Host "end: Item=[$Item]"; "total $n" }
}
'web-01', 'api-01' | Measure-Item
begin: Item=[] process: Item=[web-01] process: Item=[api-01] end: Item=[api-01] total 2
function Show-Item {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [string[]]$Item)
process { foreach ($i in $Item) { "got $i" } }
}
Show-Item -Item web-01, api-01
'web-01', 'api-01' | Show-Item
function Show-ItemBug {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [string[]]$Item)
process { "got $Item" } # forgot the foreach
}
Show-ItemBug -Item web-01, api-01
got web-01 got api-01 got web-01 got api-01 got web-01 api-01
How to verify: call the function both ways — by argument and by pipeline — and compare. Common mistake: testing only the pipeline form; with an array argument, process runs once with the whole array. Production use: every OpsKit function that takes targets follows the [string[]] + foreach pattern or, like Test-OpsEndpoint, a scalar parameter that is fed one object at a time.
function Get-Endpoint {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)] [string]$IP,
[Parameter(ValueFromPipelineByPropertyName)] [int]$Port = 80
)
process { "{0}:{1}" -f $IP, $Port }
}
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 2 | Get-Endpoint
Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json | Select-Object -First 2 | Get-Endpoint
'10.10.1.21' | Get-Endpoint
10.10.1.21:80 10.10.1.22:80 10.10.1.21:8080 10.10.1.22:8080 Get-Endpoint: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
The CSV has no Port column, so the default 80 applies per row; the JSON inventory has Port: 8080, which binds by property name. A plain string has no IP property and -IP has no ByValue — the same error you saw for 'pwsh' | Get-Process in Lesson 1.
Trace-Command -Name ParameterBinding -PSHost -Expression {
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
}
BIND NAMED cmd line args [Test-Target]
BIND POSITIONAL cmd line args [Test-Target]
MANDATORY PARAMETER CHECK on cmdlet [Test-Target]
CALLING BeginProcessing
CALLING BeginProcessing
CALLING BeginProcessing
CALLING ProcessRecord
…
BIND PIPELINE object to parameters: [Test-Target]
PIPELINE object TYPE = [Selected.System.Management.Automation.PSCustomObject]
RESTORING pipeline parameter's original values
Parameter [Target] PIPELINE INPUT ValueFromPipeline NO COERCION
BIND arg [@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}] to parameter [Target]
Executing DATA GENERATION metadata: [System.Management.Automation.ArgumentTypeConverterAttribute]
BIND arg [@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}] to param [Target] SKIPPED
Parameter [Target] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
BIND arg [10.10.1.21] to parameter [Target]
BIND arg [10.10.1.21] to param [Target] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [Test-Target]
CALLING ProcessRecord
CALLING EndProcessing
Target=[10.10.1.21]
Goal: Make servers.csv rows and plain strings both bind to -Target, then reproduce the three classic pipeline bugs. Environment: pwsh 7.6 in ~/pslab. Cost: none.
function Test-Target {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string]$Target)
process { "Target=[$Target]" }
}
'10.30.1.41' | Test-Target
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
Target=[10.30.1.41]
Target=[@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}]function Test-Target {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string]$Target
)
process { "Target=[$Target]" }
}
'10.30.1.41' | Test-Target
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
[pscustomobject]@{ ComputerName = 'build-07' } | Test-Target
Target=[10.30.1.41] Target=[10.10.1.21] Target=[build-07]
@([pscustomobject]@{ IP = '10.0.0.1' }, [pscustomobject]@{ Name = 'no-ip' }, [pscustomobject]@{ IP = '10.0.0.3' }) | Test-Target
Target=[10.0.0.1]
Target=[@{Name=no-ip}]
Target=[10.0.0.3]
If that is unacceptable, drop ValueFromPipeline (keep only ByPropertyName) — then strings must be passed as -Target — or validate with [ValidatePattern()]/[ValidateScript()].
Show-Item from the Commands tab (only got db-01). Bug 2 — forgot the foreach: Show-ItemBug -Item web-01, api-01 prints one line got web-01 api-01. Bug 3 — argument and pipeline for the same parameter:
'10.30.1.41' | Test-Target -Target 10.0.0.1
Test-Target: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
A parameter bound on the command line is no longer available for pipeline input.
Select-Object -First can stop it early:
function Write-Slow { [CmdletBinding()] param([Parameter(ValueFromPipeline)] $InputObject) process { Write-Host " emit $InputObject"; $InputObject } }
1..3 | Write-Slow | Select-Object -First 1
emit 1 1
Sort-Object):
function Get-Sorted {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Name)
begin { $all = [System.Collections.Generic.List[string]]::new() }
process { $all.Add($Name) }
end { $all | Sort-Object -Unique }
}
(Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json).Name | Get-Sorted
api-01 bastion-01 db-01 edge-01 web-01 web-02
Trace-Command example from the Commands tab and find the SKIPPED line followed by BIND arg [10.10.1.21] … SUCCESSFUL.Case 1: a patch report that listed only the last server
Problem: Get-Content servers.txt | Get-PatchLevel returned one row for a 300-line file. Root cause: Get-PatchLevel had a pipeline parameter but no process block; the body ran once, as end, with the last name. No error, so it went unnoticed for weeks. Fix: wrap the body in process { }. Prevention: a test that pipes three objects and expects three results (Lesson 8).
Case 2: DNS errors for hosts named “@{Name=…}”
Problem: A connectivity script logged thousands of “No such host is known: @{Name=web-01; Env=prod; IP=…}”. Root cause: the CMDB export renamed the column ComputerName to IP; the function's [string]$ComputerName had ValueFromPipeline, so the binder fell back to coercion. Fix: [Alias('IP', 'HostName')]; and log the bound target in verbose output so this shows up immediately.
Case 3: a pipeline function that loaded 2 million objects into memory
Problem: A log-enrichment function collected every input in begin/process and processed in end, “to be efficient”. Memory grew until the job was killed. Fix: do the per-object work in process and emit immediately; only aggregate (counts, sums) in end.
Common errors and fixes
Only the last pipeline object is processed
Cause: no process block.
Fix: process { … }; check with 1..3 | f.
The input object cannot be bound to any parameters for the command …
Cause: no parameter accepts this object ByValue and none of its property names matches a ByPropertyName parameter or alias — or the parameter was already given on the command line.
$obj | Get-Member -MemberType Properties
(Get-Command f).Parameters.Values | Where-Object { $_.Attributes.ValueFromPipelineByPropertyName -contains $true } | Select-Object Name, AliasesThe parameter receives text like @{Name=…; IP=…}
Cause: ByValue with coercion on a [string] parameter.
Fix: add the property name as an [Alias()], or remove ValueFromPipeline.
The parameter is empty in begin
Cause: pipeline values are bound per object, after begin.
Fix: move the code to process; use begin only for set-up that needs no input.
1. List the pipeline-enabled parameters of your Test-Target with their aliases.
(Get-Command Test-Target).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipeline -contains $true -or $_.Attributes.ValueFromPipelineByPropertyName -contains $true } |
Select-Object Name, Aliases2. Write Measure-Bytes that sums the Length of piped files and outputs one total.
function Measure-Bytes {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipelineByPropertyName)] [long]$Length)
begin { $sum = 0 }
process { $sum += $Length }
end { $sum }
}
Get-ChildItem ~/pslab/data -File | Measure-BytesTest-OpsEndpoint declares -Target with ValueFromPipeline and ByPropertyName, -Port with ByPropertyName only. What happens for [pscustomobject]@{ IP = '127.0.0.1'; Port = 18080 }, and what for the string '127.0.0.1'?
The object: ByValue for -Target is skipped (not a string without coercion), ByPropertyName binds IP → -Target and Port → -Port. The string: ByValue binds it to -Target; -Port keeps its default 8080. Both are verified in Module 8 and in the acceptance check “pipeline binds IP+Port”.
Verified teaching videos
Official documentation
- about_Functions_Advanced_Parameters (ValueFromPipeline…) · about_Functions_Advanced_Methods (begin/process/end) · about_Pipelines
Video storyboard (about 90 seconds)
Visual: the Lesson 1 binder guard now stands at the door of YOUR function; a CSV row shows its IP badge, and the guard checks the alias list.
Narration: declare which parameters take pipeline input — and which property names count.
Visual: three parcels arrive, but without a process station only the last is unpacked.
Narration: per-object work belongs in process.
Visual: a parcel without an IP badge is flattened into a text label “@{…}”.
Narration: string parameters accept anything; aliases make the right property win first.
Module 7 · Output and help: [OutputType], PSTypeName, comment-based help and splatting
Get-Help finds it, and pass parameters around with splatting- Declare
[OutputType()]and know it is metadata only (not enforced). - Give objects a PSTypeName, see it in
Get-MemberandPSObject.TypeNames, change their default display withUpdate-TypeData, and accept only them with[PSTypeName('OpsKit.Server')]. - Write comment-based help and place it where
Get-Helpfinds it (verified placement rules), with.PARAMETERand.EXAMPLEsections. - Use splatting (
@paramshashtables and arrays), explicit overrides,@PSBoundParametersforwarding with.Remove(), and choose approved verbs (Get-Verb).
What: three kinds of “contract” metadata
| Mechanism | Effect | Enforced? |
|---|---|---|
[OutputType('OpsKit.Server')] | Shown by Get-Command (.OutputType) and help; used by tools and completion for .NET types | No — a function declaring [int] can emit strings |
PSTypeName = 'OpsKit.Server' in [pscustomobject]@{…} | Inserted as the first entry of PSObject.TypeNames; Get-Member shows TypeName: OpsKit.Server; type data and format views can target it | It is the object's identity |
[PSTypeName('OpsKit.Server')]$Server on a parameter | Accepts only objects whose TypeNames contain that name | Yes, by the binder |
Why: help and type names make tools discoverable
Users of your functions use the same discovery workflow as for built-in cmdlets (Lesson 1 Module 3): Get-Help Get-OpsServer -Examples, Get-Command -Syntax, | Get-Member. Help for functions comes from comment-based help — no Update-Help needed. Type names let you add a tidy default view (Lesson 4 ships a .format.ps1xml; here we use Update-TypeData) and let other functions require “a server object, not just any object”.
How: where comment-based help must go (verified)
| Placement | Get-Help on 7.6.10 |
|---|---|
Directly above function (no blank line) | ✓ found |
Above function with one blank line between | ✓ found |
| Above with two blank lines | ✗ ignored (shows only the name) |
| First thing inside the body (OpsKit style) | ✓ found |
Inside the body but after [CmdletBinding()] param() | ✗ ignored (shows the syntax) |
| Last thing in the body | ✓ found |
For scripts, Lesson 1 found the matching rule: the help block must come before #Requires. Keyword spelling matters (.SYNOPSIS, .DESCRIPTION, .PARAMETER Name, .EXAMPLE, .OUTPUTS); an unknown keyword makes the whole block invalid.
When: splatting and forwarding
Splatting passes a hashtable as named parameters (Get-OpsServer @p) or an array as positional ones. It keeps long calls readable, lets you build parameters conditionally (if ($Role) { $p.Role = $Role }), and in 7.x an explicit parameter after the splat overrides the splatted value. @PSBoundParameters forwards exactly what your caller passed (including -Verbose) to an inner command — remove the keys the inner command does not have, or it fails with “A parameter cannot be found …”.
[OutputType] converts or checks output” — it is documentation. ② “Splatting works with $p” — Get-OpsServer $p passes the hashtable as one positional value; you need @p. ③ “Help can go anywhere in the function” — it cannot follow param(). ④ “Select-Object -First 1 returns the same object” — for a [pscustomobject] it adds the type name Selected.System.Management.Automation.PSCustomObject in front (verified on 7.6.10), so code that checks TypeNames[0] breaks; check with -contains. ⑤ “Any verb is fine” — unapproved verbs produce an import warning and confuse discovery.Diagram: one object, several readers of its type name
Diagram: splatting and forwarding
Help-block placement checker (and other contract checks)
Choose a placement or a call and step through how PowerShell finds help, matches type names or expands a splat. Outcomes reproduced on 7.6.10.
Command reference
| Syntax | Purpose | Notes |
|---|---|---|
[OutputType('Type.Name', ParameterSetName = 'X')] | Declare output per set | Several attributes allowed |
[pscustomobject]@{ PSTypeName = 'OpsKit.Server'; … } | Name the object's type | First key-like entry, not a property |
$o.PSObject.TypeNames / $o.pstypenames | Inspect type names | Most specific first |
Update-TypeData -TypeName T -DefaultDisplayPropertySet a, b | Default columns for a type | Session only; Lesson 4 uses files |
[PSTypeName('T')]$p | Accept only objects of type name T | Works with pipeline input |
<# .SYNOPSIS … .PARAMETER X … .EXAMPLE … #> | Comment-based help | See placement table |
Get-Help f -Examples / -Parameter X / -Full | Read it | Works offline |
cmd @hash, cmd @array | Splatting | Explicit parameters override the splat |
inner @PSBoundParameters | Forward caller's parameters | .Remove('X') what inner lacks |
Get-Verb, Get-Verb -Verb Fetch | Approved verbs | 100 in 7.6; nothing for unapproved ones |
. ~/pslab/OpsKit/OpsKit.ps1
(Get-Command Get-OpsServer).OutputType.Name
(Get-Command Get-OpsConfig).OutputType | Format-Table Name, Type -AutoSize
function Get-Number { [CmdletBinding()] [OutputType([int])] param() 'not a number' }
(Get-Number).GetType().Name
OpsKit.Server Name Type ---- ---- OpsKit.EnvConfig System.Collections.Hashtable System.Collections.Hashtable String
$s = Get-OpsServer -Env prod -Name edge-01 $s.PSObject.TypeNames Get-OpsServer -Env dev | Get-Member -MemberType NoteProperty
OpsKit.Server System.Management.Automation.PSCustomObject System.Object TypeName: OpsKit.Server Name MemberType Definition ---- ---------- ---------- Env NoteProperty string Env=dev IP NoteProperty string IP=10.10.1.21 Monitored NoteProperty bool Monitored=True Name NoteProperty string Name=web-01 Port NoteProperty int Port=8080 Region NoteProperty string Region=canadacentral Role NoteProperty string[] Role=System.String[]
Get-OpsServer -Env dev | Format-Table Update-TypeData -TypeName OpsKit.Server -DefaultDisplayPropertySet Name, Env, Role, IP -Force Get-OpsServer -Env dev
Name Env Role IP Port Region Monitored
---- --- ---- -- ---- ------ ---------
web-01 dev {web} 10.10.1.21 8080 canadacentral True
api-01 dev {api} 10.10.1.22 8080 canadacentral True
db-01 dev {db} 10.10.1.23 8080 canadacentral False
Name Env Role IP
---- --- ---- --
web-01 dev {web} 10.10.1.21
api-01 dev {api} 10.10.1.22
db-01 dev {db} 10.10.1.23
How to verify: without type data, 7 properties are shown as a list (Lesson 1: 5+ properties → list); with a 4-property default display set they appear as a table, and Format-List * still shows everything. Common mistake: putting Format-Table inside the function to get a nice view — that destroys the objects. Production use: Lesson 4 moves this into OpsKit.format.ps1xml/types.ps1xml loaded by the module manifest.
function Show-Server {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [PSTypeName('OpsKit.Server')] $Server)
process { "{0} ({1}) at {2}" -f $Server.Name, $Server.Env, $Server.IP }
}
Get-OpsServer -Env staging | Show-Server
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Show-Server
$first = Get-OpsServer -Env dev | Select-Object -First 1
$first.PSObject.TypeNames
$first | Show-Server
$first.PSObject.TypeNames -contains 'OpsKit.Server'
web-01 (staging) at 10.20.1.31 api-01 (staging) at 10.20.1.32 db-01 (staging) at 10.20.1.33 Show-Server: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. Selected.System.Management.Automation.PSCustomObject OpsKit.Server System.Management.Automation.PSCustomObject System.Object web-01 (dev) at 10.10.1.21 True
$p = @{
Env = 'prod'
Role = 'web'
}
Get-OpsServer @p | Select-Object -ExpandProperty Name
Get-OpsServer @p -Role api | Select-Object -ExpandProperty Name # explicit wins
$positional = @('prod')
Get-OpsServer @positional -Role db | Select-Object -ExpandProperty IP
Get-OpsServer $p
Get-OpsServer @p -Port 22
web-01 web-02 edge-01 api-01 edge-01 10.30.1.44 Get-OpsServer: Cannot validate argument on parameter 'Env'. The argument "System.Collections.Hashtable" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. Get-OpsServer: A parameter cannot be found that matches parameter name 'Port'.
Goal: Verify the help placement rules yourself, read OpsKit's help, and write a forwarding wrapper. Environment: pwsh 7.6, OpsKit from Module 8 (do Module 8 first if you prefer). Cost: none.
~/pslab/scripts/help-test.ps1:
<#
.SYNOPSIS
Help directly above the function (no blank line).
#>
function Get-HelpAbove { 'x' }
<#
.SYNOPSIS
Help with ONE blank line before the function.
#>
function Get-HelpOneBlank { 'x' }
<#
.SYNOPSIS
Help with TWO blank lines before the function.
#>
function Get-HelpTwoBlank { 'x' }
function Get-HelpInside {
<#
.SYNOPSIS
Help as the first thing inside the body.
#>
'x'
}
function Get-HelpAfterAttr {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Help after param() - not the start of the body.
#>
'x'
}
function Get-HelpAtEnd {
'x'
<#
.SYNOPSIS
Help as the last thing in the body.
#>
}
. ~/pslab/scripts/help-test.ps1
'Get-HelpAbove', 'Get-HelpOneBlank', 'Get-HelpTwoBlank', 'Get-HelpInside', 'Get-HelpAfterAttr', 'Get-HelpAtEnd' |
ForEach-Object { '{0,-18} -> {1}' -f $_, (Get-Help $_).Synopsis.Trim() }
Get-HelpAbove -> Help directly above the function (no blank line). Get-HelpOneBlank -> Help with ONE blank line before the function. Get-HelpTwoBlank -> Get-HelpTwoBlank Get-HelpInside -> Help as the first thing inside the body. Get-HelpAfterAttr -> Get-HelpAfterAttr [<CommonParameters>] Get-HelpAtEnd -> Help as the last thing in the body.
Get-Help Get-OpsServer -Parameter Role Get-Help Test-OpsEndpoint -Parameter Target
-Role <String>
A role such as web, api, db or bastion. 'web' also matches the multi-role server edge-01.
Required? false
Position? named
Default value *
Accept pipeline input? false
Aliases
Accept wildcard characters? true
-Target <String>
Host name or IP address. Aliases: IP, ComputerName, HostName.
Required? true
Position? 1
Default value
Accept pipeline input? true (ByValue, ByPropertyName)
Aliases
Accept wildcard characters? false
Two details: Accept wildcard characters? true comes from [SupportsWildcards()]; and the Aliases line stays empty for functions on 7.6.10 even though [Alias()] works — that is why the alias names are repeated in the .PARAMETER text.
function Get-OpsProdServer {
[CmdletBinding()]
param([string]$Role = '*', [string]$Name = '*')
Get-OpsServer -Env prod @PSBoundParameters
}
Get-OpsProdServer -Role db | Select-Object Name, Env, IP
Get-OpsProdServer -Role web -Verbose | Select-Object -ExpandProperty Name
Name Env IP ---- --- -- db-01 prod 10.30.1.44 VERBOSE: Reading C:\Users\labadmin\pslab\data\inventory.json web-01 web-02 edge-01
-Verbose was forwarded too (it is in $PSBoundParameters), so the inner Write-Verbose fired.
function Get-OpsWebServer {
[CmdletBinding()]
param([string]$Env, [switch]$Detailed)
Get-OpsServer @PSBoundParameters -Role web
}
Get-OpsWebServer -Env dev -Detailed
function Get-OpsWebServer {
[CmdletBinding()]
param([string]$Env, [switch]$Detailed)
$null = $PSBoundParameters.Remove('Detailed')
$servers = Get-OpsServer @PSBoundParameters -Role web
if ($Detailed) { $servers | Format-List } else { $servers.Name }
}
Get-OpsWebServer -Env prod
Get-OpsWebServer: A parameter cannot be found that matches parameter name 'Detailed'. web-01 web-02 edge-01
Get-Verb -Verb Get, Test, Invoke, Fetch, Check | Format-Table Verb, AliasPrefix, Group -AutoSize
(Get-Verb).Count
Set-Content ~/pslab/tmp/BadVerb.psm1 -Value 'function Fetch-OpsServer { }; function Check-OpsEndpoint { }'
Import-Module ~/pslab/tmp/BadVerb.psm1
Remove-Module BadVerb
Verb AliasPrefix Group ---- ----------- ----- Get g Common Test t Diagnostic Invoke i Lifecycle 100 WARNING: The names of some imported commands from the module 'BadVerb' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
Case 1: a check that failed only after a refactor added Select-Object
Problem: While writing this lesson's acceptance script, the check (Get-OpsServer -Env dev | Select-Object -First 1).PSObject.TypeNames[0] returned Selected.System.Management.Automation.PSCustomObject instead of OpsKit.Server. Root cause: Select-Object on a [pscustomobject] prepends a Selected.* type name even with only -First (the OpsKit.Server name is still in the list; Process and DirectoryInfo objects were not affected in the same test). Fix: index the result instead (@(Get-OpsServer -Env dev)[0]), and test type names with -contains or [PSTypeName()] rather than [0].
Case 2: “Get-Help shows nothing useful for our module”
Problem: A team's functions all had help blocks, but Get-Help showed only syntax. Root cause: a style guide put the help block after [CmdletBinding()] param() “so the parameters are visible first”. Fix: move it to the start of the body; add a Pester test that every exported command has a synopsis (Lesson 8).
Case 3: a wrapper whose -Verbose vanished into a legacy function
Problem: An advanced wrapper forwarded @PSBoundParameters to an old simple function. Calls with -Verbose did not fail — the legacy function silently received -Verbose: True in $args (reproduced on 7.6.10: name=web-01 args=[-Verbose: True]). Root cause: splatting a hashtable into a simple function cannot be checked, because simple functions accept anything. Fix: make the inner function advanced (then it honours -Verbose), or build the parameter hashtable explicitly. The same care applies to -ProgressAction, a common parameter only since 7.4, when you forward to commands in older sessions.
Common errors and fixes
Get-Help shows only the syntax of my function
Cause: help block in the wrong place (after param(), two blank lines above), or an invalid keyword.
Fix: move it to the first line of the body; check keywords against about_Comment_Based_Help.
Splatting passes “System.Collections.Hashtable” as a value
Cause: $p instead of @p.
A parameter cannot be found that matches parameter name 'X' — while forwarding
Cause: $PSBoundParameters contains a parameter the inner command lacks.
$null = $PSBoundParameters.Remove('X')My [PSTypeName()] parameter rejects objects that look right
Cause: they were rebuilt (e.g. Import-Csv, ConvertFrom-Json, Select-Object Name, IP with properties) and lost the type name.
Fix: re-create them through the function that adds the type name, or relax the parameter type.
1. Build parameters conditionally and splat them.
$p = @{ Env = 'prod' }
if ($onlyWeb) { $p.Role = 'web' }
Get-OpsServer @p2. Find every OpsKit function without a synopsis.
Get-Command -Name *-Ops* -CommandType Function |
Where-Object { (Get-Help $_.Name).Synopsis -match '^\s*\S+-\S+ ' -or -not (Get-Help $_.Name).Synopsis } |
Select-Object -ExpandProperty NameWhen there is no help, Synopsis contains the syntax line instead. In v0.1 this finds Get-OpsDataPath, the private helper.
Should Get-OpsServer format its own output (e.g. end with | Format-Table) so users get a neat table?
No. Format-Table turns objects into format records; Get-OpsServer | Test-OpsEndpoint would break. Keep emitting typed objects and control the default view with type data (Update-TypeData now, a format file in Lesson 4). Users can still pipe to Format-Table themselves at the end.
Verified teaching videos
No verified video was found for comment-based help placement or PSTypeName specifically; use the experiment in the Lab.
Official documentation
- about_Comment_Based_Help · about_Functions_OutputTypeAttribute · about_Splatting · Update-TypeData · Everything about PSCustomObject · Approved verbs
Video storyboard (about 90 seconds)
Visual: an object gets a name badge “OpsKit.Server”; Get-Member reads it.
Narration: a type name gives your objects an identity.
Visual: help blocks slide toward a function; one stops two lines away and falls off.
Narration: help goes at the top of the body or right above the function.
Visual: a hashtable explodes into named parameters (@p); a wrapper passes along a bag of $PSBoundParameters.
Narration: splat for readability, forward what the caller passed.
Module 8 · OpsKit v0.1: Get-OpsServer, Get-OpsConfig and Test-OpsEndpoint
- Write
Get-OpsServer(-EnvwithValidateSet, wildcard-Role/-Name) returningOpsKit.Serverobjects with real types (Portas[int],Roleas[string[]]). - Write
Get-OpsConfigwith two parameter sets,Import-PowerShellDataFile(data only, no code execution) and aDefaultEnvfallback detected with$PSBoundParameters. - Write
Test-OpsEndpoint: pipeline input by value and by property name (IP/ComputerName/HostName+Port),begin/process/end, aTcpClientconnect with a timeout, and one result object per target. - Load OpsKit with the dot-sourced loader and run
Get-OpsServer -Env prod | Test-OpsEndpoint, interpreting Open / Timeout / ConnectionRefused / HostNotFound.
What: OpsKit v0.1
| File | Function | Techniques from this lesson |
|---|---|---|
Private/Get-OpsDataPath.ps1 | Resolve ~/pslab/data/… (override with $env:OPSKIT_DATA) | Advanced function, [OutputType([string])] |
Public/Get-OpsServer.ps1 | Servers from inventory.json | ValidateSet, Position, [SupportsWildcards()], ValidateScript + ErrorMessage, Write-Verbose, PSTypeName, help |
Public/Get-OpsConfig.ps1 | One environment's settings, or -All | Parameter sets, DefaultParameterSetName, [Alias('Environment')], $PSCmdlet.ParameterSetName, $PSBoundParameters.ContainsKey, two [OutputType]s |
Public/Test-OpsEndpoint.ps1 | TCP port check | ValueFromPipeline + ByPropertyName, [Alias('IP','ComputerName','HostName')], ValidateRange, ValidateNotNullOrEmpty, begin/process/end |
Why: a TCP check instead of ping
ICMP is often blocked, and a host that answers ping can still have a dead service. Opening a TCP connection to the service port answers the real question. [System.Net.Sockets.TcpClient]::new().ConnectAsync($host, $port).Wait($ms) gives a bounded wait: Test-NetConnection (Windows only) and Test-Connection -TcpPort are alternatives, but the .NET call works the same on every platform and lets us control the timeout precisely. Failures surface as a SocketException wrapped in an AggregateException; GetBaseException() unwraps it, and SocketErrorCode gives a stable name (ConnectionRefused, HostNotFound, …).
How: what the results mean (verified on Windows 11, 7.6.10)
| Situation | Result | Why |
|---|---|---|
Local TcpListener on 127.0.0.1:18080 | Open in ~0–15 ms | The OS completes the handshake from the listen backlog, even without AcceptTcpClient() |
| 127.0.0.1:18081 (nothing listening), timeout 500 ms | Timeout | On Windows a refused loopback connection is only reported after ~1 s (measured 1032 ms); with -TimeoutMs 5000 you get ConnectionRefused. On Linux a refusal is typically immediate |
localhost:18080, listener on IPv4 only | Timeout at 500 ms; Open after ~1 s with a longer timeout | localhost resolves to ::1 first, then 127.0.0.1; the IPv6 attempt is refused first |
| 10.30.x.x inventory addresses | Timeout | Fictitious private addresses: nothing answers, so the full timeout elapses (~300 ms each with -TimeoutMs 300) |
nosuchhost.invalid | HostNotFound | DNS failure; .invalid is reserved and never resolves |
When: v0.1 limits (fixed in later lessons)
- Functions are dot-sourced into the session, so “private” helpers are visible and every function can see your variables (Lesson 4: module scope).
- Tests run one after another: 6 unreachable servers × 300 ms ≈ 2 s; 600 servers would take minutes (Lesson 6:
Invoke-OpsHealthCheckin parallel). - No retries, no structured logging, no
-WhatIf— nothing changes state yet (Lesson 5).
localhost = 127.0.0.1” — not when IPv6 is tried first. ③ “A TCP connect proves the service works” — it proves something accepts connections; Lesson 7 adds HTTP health checks. ④ “Import-PowerShellDataFile is like dot-sourcing a .psd1” — it parses data only and refuses code, which is why it is safe for configuration. ⑤ “Running the loader with ./OpsKit.ps1 loads OpsKit” — only dot-sourcing does (Module 2).Diagram: OpsKit v0.1 data flow
Diagram: one connection attempt with a timeout
Endpoint test walk-through
Choose a target and step through binding, validation, the connection attempt and the result object. All results are real 7.6.10 runs on Windows 11. Below the animation is the interactive troubleshooting tree for OpsKit functions.
Interactive troubleshooting tree: my function does not behave
Command reference
| Command | Purpose | Notes |
|---|---|---|
. ~/pslab/OpsKit/OpsKit.ps1 | Load OpsKit v0.1 | Dot, space, path |
Get-OpsServer [-Env] <string[]> [-Role] [-Name] [-Path] | Inventory objects | OpsKit.Server |
Get-OpsConfig [[-Env] <string>] / Get-OpsConfig -All | Configuration | Two parameter sets |
Test-OpsEndpoint [-Target] <string> [[-Port] <int>] [-TimeoutMs] | TCP check | Pipeline by value or property name |
[System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080) | Local test endpoint | .Start() / .Stop() |
Import-PowerShellDataFile | Read .psd1 safely | No code execution |
. ~/pslab/OpsKit/OpsKit.ps1 Get-Command -Name *-Ops* | Format-Table CommandType, Name, Source -AutoSize (Get-OpsServer).Count Get-OpsServer -Env prod -Role web | Format-Table Name, Env, Role, IP Get-OpsServer prod, staging -Role db | Format-Table Name, Env, IP Get-OpsServer -Name 'web-*' -Env dev, prod | Format-Table Name, Env
CommandType Name Source
----------- ---- ------
Function Get-OpsConfig
Function Get-OpsDataPath
Function Get-OpsServer
Function Test-OpsEndpoint
12
Name Env Role IP
---- --- ---- --
web-01 prod {web} 10.30.1.41
web-02 prod {web} 10.30.1.42
edge-01 prod {web, api} 10.30.2.51
Name Env IP
---- --- --
db-01 staging 10.20.1.33
db-01 prod 10.30.1.44
Name Env
---- ---
web-01 dev
web-01 prod
web-02 prod
Note Source is empty: these are loose functions, not module commands. After Lesson 4 the column shows OpsKit. And edge-01 (role "web,api") matches -Role web because the function splits the role string into an array.
Get-OpsConfig -Env prod Get-OpsConfig -Verbose | Format-List Env, Region, HealthUrl (Get-OpsConfig -All).Health Get-OpsConfig -Env prod -All Get-Command Get-OpsConfig -Syntax
Env : prod
Region : canadacentral
HealthUrl : https://shop.example.com/healthz
RequireConfirm : True
TimeoutSec : 5
Retries : 3
VERBOSE: No -Env given; using DefaultEnv 'dev'
Env : dev
Region : canadacentral
HealthUrl : http://10.10.1.21:8080/healthz
Name Value
---- -----
TimeoutSec 5
BackoffSec {1, 2, 4}
Retries 3
Get-OpsConfig: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
Get-OpsConfig [[-Env] <string>] [-Path <string>] [<CommonParameters>]
Get-OpsConfig -All [-Path <string>] [<CommonParameters>]
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
Test-OpsEndpoint -Target 127.0.0.1 -Port 18080
'127.0.0.1', 'localhost' | Test-OpsEndpoint -Port 18080 | Format-Table Target, Port, Open, Result
Test-OpsEndpoint localhost 18080 -TimeoutMs 5000 | Format-Table Target, Port, Open, Result, Ms -AutoSize
Test-OpsEndpoint 127.0.0.1 18081 -TimeoutMs 5000 | Format-Table Target, Port, Open, Result, Ms -AutoSize
[System.Net.Dns]::GetHostAddresses('localhost').IPAddressToString
$listener.Stop()
Name : Target : 127.0.0.1 Port : 18080 Open : True Result : Open Ms : 13 Target Port Open Result ------ ---- ---- ------ 127.0.0.1 18080 True Open localhost 18080 False Timeout Target Port Open Result Ms ------ ---- ---- ------ -- localhost 18080 True Open 1004 Target Port Open Result Ms ------ ---- ---- ------ -- 127.0.0.1 18081 False ConnectionRefused 1033 ::1 127.0.0.1
How to verify: the 1-second figures are the Windows TCP stack retrying refused connections; they explain why localhost times out at 500 ms while 127.0.0.1 is instant. Common mistake: testing localhost against an IPv4-only listener and concluding the service is down. Production use: test the exact address the clients use; record Result, not just Open, so a refusal (service down) is distinguishable from a timeout (firewall/routing).
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 -Verbose | Format-Table Name, Target, Port, Open, Result, Ms -AutoSize
@(
[pscustomobject]@{ Name = 'local-ok'; ComputerName = '127.0.0.1'; Port = 18080 }
[pscustomobject]@{ Name = 'local-off'; ComputerName = '127.0.0.1'; Port = 18081 }
[pscustomobject]@{ Name = 'bad-dns'; HostName = 'nosuchhost.invalid'; Port = 443 }
) | Test-OpsEndpoint | Format-Table Name, Target, Port, Open, Result -AutoSize
Test-OpsEndpoint -Target 127.0.0.1 -Port 70000
VERBOSE: 0 of 6 endpoint(s) open Name Target Port Open Result Ms ---- ------ ---- ---- ------ -- web-01 10.30.1.41 8080 False Timeout 312 web-02 10.30.1.42 8080 False Timeout 310 api-01 10.30.1.43 8080 False Timeout 310 edge-01 10.30.2.51 8080 False Timeout 309 db-01 10.30.1.44 8080 False Timeout 310 bastion-01 10.30.2.10 8080 False Timeout 310 Name Target Port Open Result ---- ------ ---- ---- ------ local-ok 127.0.0.1 18080 True Open local-off 127.0.0.1 18081 False Timeout bad-dns nosuchhost.invalid 443 False HostNotFound Test-OpsEndpoint: Cannot validate argument on parameter 'Port'. The 70000 argument is greater than the maximum allowed range of 65535. Supply an argument that is less than or equal to 65535 and then try the command again.
The 10.x timeouts are expected: the inventory addresses do not exist on your network. The VERBOSE line comes from the end block, after the last object; it appears above the table because Format-Table -AutoSize holds all rows until the pipeline ends, while verbose messages are written immediately. Without -AutoSize, Format-Table sizes columns from the first rows (in one of our runs it truncated edge-01 to edge-…) and the VERBOSE line came after the rows.
Goal: Write OpsKit v0.1 and run it end to end. Environment: pwsh 7.6, VS Code, ~/pslab/OpsKit from Module 0. Cost: none; the listener binds only to loopback.
~/pslab/OpsKit/Private/Get-OpsDataPath.ps1:
function Get-OpsDataPath {
# Private helper: where the course data lives. $env:OPSKIT_DATA overrides the
# default (Lesson 8's tests use that). Until Lesson 4, "Private" is only a folder
# name: dot-sourcing makes this function visible in your session like any other.
[CmdletBinding()]
[OutputType([string])]
param(
[string]$ChildPath
)
$root = if ($env:OPSKIT_DATA) { $env:OPSKIT_DATA } else { Join-Path $HOME 'pslab' 'data' }
if ($ChildPath) { Join-Path $root $ChildPath } else { $root }
}Get-OpsServer — ~/pslab/OpsKit/Public/Get-OpsServer.ps1:
function Get-OpsServer {
<#
.SYNOPSIS
Lists servers from the OpsKit inventory.
.DESCRIPTION
Reads inventory.json and returns one OpsKit.Server object per server.
Filter with -Env, -Role and -Name; -Role and -Name accept wildcards.
.PARAMETER Env
One or more environments: dev, staging, prod. All environments if omitted.
.PARAMETER Role
A role such as web, api, db or bastion. 'web' also matches the multi-role server edge-01.
.PARAMETER Name
Server name filter, for example 'web-*'.
.PARAMETER Path
The inventory file. Default: ~/pslab/data/inventory.json.
.EXAMPLE
Get-OpsServer -Env prod -Role web
.EXAMPLE
Get-OpsServer -Env prod | Test-OpsEndpoint
.OUTPUTS
OpsKit.Server
#>
[CmdletBinding()]
[OutputType('OpsKit.Server')]
param(
[Parameter(Position = 0)]
[ValidateSet('dev', 'staging', 'prod')]
[string[]]$Env,
[SupportsWildcards()]
[string]$Role = '*',
[SupportsWildcards()]
[string]$Name = '*',
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf },
ErrorMessage = 'Inventory file not found: {0}')]
[string]$Path = (Get-OpsDataPath -ChildPath 'inventory.json')
)
Write-Verbose "Reading $Path"
$inventory = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
foreach ($s in $inventory) {
if ($Env -and $s.Env -notin $Env) { continue }
if ($s.Name -notlike $Name) { continue }
$roles = $s.Role -split ','
if (-not ($roles -like $Role)) { continue }
[pscustomobject]@{
PSTypeName = 'OpsKit.Server'
Name = $s.Name
Env = $s.Env
Role = $roles
IP = $s.IP
Port = [int]$s.Port
Region = $s.Region
Monitored = [bool]$s.Monitored
}
}
}
$roles -like $Role applied to an array returns the matching elements (Lesson 2: operators on arrays), so -not (…) means “no role matched”. The parameter is called $Env; that is unrelated to the $env: drive (Module 2 quiz).
Get-OpsConfig — ~/pslab/OpsKit/Public/Get-OpsConfig.ps1:
function Get-OpsConfig {
<#
.SYNOPSIS
Reads the OpsKit configuration file (opskit.config.psd1).
.DESCRIPTION
Uses Import-PowerShellDataFile, which parses the file as data and never runs code.
Returns the settings of one environment (DefaultEnv from the file when -Env is
omitted); -All returns the whole configuration as a hashtable.
.PARAMETER Env
dev, staging or prod. Alias: Environment.
.PARAMETER All
Return the complete configuration hashtable.
.EXAMPLE
Get-OpsConfig -Env prod
.EXAMPLE
(Get-OpsConfig -All).Health.TimeoutSec
#>
[CmdletBinding(DefaultParameterSetName = 'Env')]
[OutputType('OpsKit.EnvConfig', ParameterSetName = 'Env')]
[OutputType([hashtable], ParameterSetName = 'All')]
param(
[Parameter(ParameterSetName = 'Env', Position = 0)]
[Alias('Environment')]
[ValidateSet('dev', 'staging', 'prod')]
[string]$Env,
[Parameter(ParameterSetName = 'All', Mandatory)]
[switch]$All,
[string]$Path = (Get-OpsDataPath -ChildPath 'opskit.config.psd1')
)
$config = Import-PowerShellDataFile -LiteralPath $Path
if ($PSCmdlet.ParameterSetName -eq 'All') {
return $config
}
if (-not $PSBoundParameters.ContainsKey('Env')) {
$Env = $config.DefaultEnv
Write-Verbose "No -Env given; using DefaultEnv '$Env'"
}
$e = $config.Environments[$Env]
[pscustomobject]@{
PSTypeName = 'OpsKit.EnvConfig'
Env = $Env
Region = $e.Region
HealthUrl = $e.HealthUrl
RequireConfirm = [bool]$e.RequireConfirm
TimeoutSec = $config.Health.TimeoutSec
Retries = $config.Health.Retries
}
}Test-OpsEndpoint — ~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1:
function Test-OpsEndpoint {
<#
.SYNOPSIS
Tests whether a TCP port answers, with a short timeout.
.DESCRIPTION
Accepts host names or IP addresses as arguments or from the pipeline.
Objects with an IP, ComputerName or HostName property (Get-OpsServer,
Import-Csv servers.csv) bind by property name; a Port property binds too.
.PARAMETER Target
Host name or IP address. Aliases: IP, ComputerName, HostName.
.PARAMETER Port
TCP port, 1-65535. Default 8080 (the inventory's port).
.PARAMETER TimeoutMs
How long to wait for each connection, in milliseconds. Default 500.
.EXAMPLE
Test-OpsEndpoint -Target 127.0.0.1 -Port 18080
.EXAMPLE
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300
.OUTPUTS
OpsKit.EndpointResult
#>
[CmdletBinding()]
[OutputType('OpsKit.EndpointResult')]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName', 'HostName')]
[ValidateNotNullOrEmpty()]
[string]$Target,
[Parameter(Position = 1, ValueFromPipelineByPropertyName)]
[ValidateRange(1, 65535)]
[int]$Port = 8080,
[Parameter(ValueFromPipelineByPropertyName)]
[string]$Name,
[ValidateRange(50, 30000)]
[int]$TimeoutMs = 500
)
begin {
$tested = 0
$open = 0
}
process {
$tested++
$client = [System.Net.Sockets.TcpClient]::new()
$timer = [System.Diagnostics.Stopwatch]::StartNew()
$result = 'Open'
try {
if (-not $client.ConnectAsync($Target, $Port).Wait($TimeoutMs)) {
$result = 'Timeout'
}
}
catch {
# Wait() wraps socket errors in an AggregateException
$inner = $_.Exception.GetBaseException()
$result = if ($inner -is [System.Net.Sockets.SocketException]) { [string]$inner.SocketErrorCode } else { $inner.Message }
}
finally {
$timer.Stop()
$client.Dispose()
}
if ($result -eq 'Open') { $open++ }
[pscustomobject]@{
PSTypeName = 'OpsKit.EndpointResult'
Name = $Name
Target = $Target
Port = $Port
Open = $result -eq 'Open'
Result = $result
Ms = [int]$timer.ElapsedMilliseconds
}
}
end {
Write-Verbose "$open of $tested endpoint(s) open"
}
}. ~/pslab/OpsKit/OpsKit.ps1, then run the first two blocks of the Commands tab. Check Get-Help Get-OpsServer -Examples and Get-OpsServer -Env dev | Get-Member (TypeName OpsKit.Server, Port is int, Role is string[]).$listener.Stop() Test-OpsEndpoint 127.0.0.1 18080 | Select-Object Target, Port, Result
Target Port Result ------ ---- ------ 127.0.0.1 18080 Timeout
IP; no Port column → default 8080):
Import-Csv ~/pslab/data/servers.csv | Where-Object Env -eq 'dev' | Test-OpsEndpoint -TimeoutMs 200 | Format-Table Name, Target, Port, Result
Name Target Port Result ---- ------ ---- ------ web-01 10.10.1.21 8080 Timeout api-01 10.10.1.22 8080 Timeout db-01 10.10.1.23 8080 Timeout
$listener.Stop() ran (or close the terminal). The OpsKit files stay — the integrated lab and Lesson 4 use them.Case 1: “all endpoints down” after a network change
Problem: A morning check reported every prod endpoint as down. Root cause: the check only recorded Open = False; in fact all results were Timeout because the monitoring host had been moved to a VLAN without a route to the servers — the services were fine. Fix: keep the Result code (Timeout vs ConnectionRefused vs HostNotFound) and group by it: … | Group-Object Result. Many timeouts at once usually point to the network path, refusals to the service.
Case 2: a health check that took 20 minutes
Problem: A script used Test-NetConnection against 400 hosts; unreachable ones took ~20 s each. Fix: a bounded connect like Test-OpsEndpoint -TimeoutMs 500, and parallelism (Lesson 6). Always budget: hosts × timeout ÷ parallelism.
Case 3: configuration that executed code
Problem: A tool loaded its settings with . ./settings.ps1; a well-meant edit added a Remove-Item line that ran on every start. Fix: store settings in a .psd1 and read them with Import-PowerShellDataFile, which only accepts literal data (strings, numbers, arrays, hashtables, $true/$false/$null).
Common errors and fixes
The term 'Get-OpsServer' is not recognized …
Cause: OpsKit not loaded in this session, or loaded with &/./ instead of dot-sourcing.
. ~/pslab/OpsKit/OpsKit.ps1 Get-Command -Name *-Ops*
Cannot validate argument on parameter 'Path'. Inventory file not found: …
Cause: ~/pslab/data missing, or $env:OPSKIT_DATA points elsewhere.
Fix: ~/pslab/New-LabData.ps1; Get-OpsDataPath shows the folder in use.
Every result is Timeout, even for 127.0.0.1
Cause: listener not started or already stopped, wrong port, or a refused connection slower than -TimeoutMs on Windows.
Fix: $listener.Server.IsBound; retry with -TimeoutMs 5000 to see ConnectionRefused.
Exception calling "Start" with "0" argument(s): "Only one usage of each socket address (protocol/network address/port) is normally permitted."
Cause: port 18080 already in use (perhaps a listener from an earlier step).
Fix: $listener.Stop(), or choose another port: Get-NetTCPConnection -LocalPort 18080 (Windows) shows the owner.
1. Show prod servers whose endpoint is not open, with the reason, sorted by name.
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 |
Where-Object { -not $_.Open } | Sort-Object Name | Select-Object Name, Target, Result2. Use the configured health timeout of an environment for the test.
$cfg = Get-OpsConfig -Env staging Get-OpsServer -Env staging | Test-OpsEndpoint -TimeoutMs ($cfg.TimeoutSec * 1000)
5 s per unreachable server — fine for 3 servers, too slow for many (Lesson 6).
Why does Test-OpsEndpoint emit one result object per target instead of writing “OK”/“FAILED” text?
Objects keep the details (target, port, result code, latency), can be filtered, grouped, exported to JSON/CSV and asserted in tests. Text would force the next consumer to parse it again — the exact problem PowerShell was designed to remove (Lesson 1).
Verified teaching videos
No verified video covers TCP checks with TcpClient timeouts; use this module and the .NET documentation.
Official documentation
Video storyboard (about 90 seconds)
Visual: three files land in Public/, a loader dot-sources them into the session.
Narration: OpsKit v0.1 is three functions and a loader.
Visual: server objects flow into Test-OpsEndpoint; IP and Port badges snap into parameters.
Narration: pipeline binding by property name makes the tools compose.
Visual: a result board: one green Open (local listener), six amber Timeout.
Narration: keep the reason, not just pass or fail.
Command cheat sheet
1. Functions and output
function Get-X { param([string]$Name = 'x') "out $Name" }
Get-X -Name a; Get-X a # NOT Get-X(a, b)
$null = $list.Add($i) # discard (fastest)
[void]$sb.Append('x'); cmd | Out-Null
return # exit only; earlier output stays
, $array # emit the array as ONE object
Write-Output $list -NoEnumerate
@(Get-X).Count # caller-side: always an array2. Scope
$x # read: walks up the CALL chain
$x = 1 # write: current scope only
$script:x++; $global:x = 1; $private:x = 's'
Get-Variable x -Scope 1 # parent scope
. ./lib.ps1 # dot-source: stays in your scope
. ~/pslab/OpsKit/OpsKit.ps1 # load OpsKit v0.1
1..3 | ForEach-Object -Parallel { $using:x }
{ $x }.GetNewClosure()3. Advanced functions
function Get-Y {
[CmdletBinding()]
param([string]$Name)
Write-Verbose "name=$Name" # -Verbose
if ($PSBoundParameters.ContainsKey('Name')) { … }
$PSCmdlet.ParameterSetName
}
(Get-Command Get-Y).CmdletBinding # True
Get-Y -Nmae x # error: parameter cannot be found4. Parameters and sets
[CmdletBinding(DefaultParameterSetName = 'ByEnv')]
param(
[Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName')]
[string]$Name,
[Parameter(ParameterSetName = 'ByEnv')] [string]$Env = 'dev',
[Alias('Address')] [ipaddress]$IP,
[switch]$Force, # -Force:$false
[Parameter(Mandatory)] [AllowEmptyString()] [string]$Note
)
Get-Command Get-Node -Syntax5. Validation and completion
[ValidateSet('dev', 'staging', 'prod')]
[ValidatePattern('^[a-z]+-\d{2}$', ErrorMessage = 'bad name {0}')]
[ValidateRange(1, 65535)] [ValidateRange('Positive')]
[ValidateScript({ Test-Path $_ }, ErrorMessage = 'not found: {0}')]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrWhiteSpace()]
[ArgumentCompletions('a', 'b')]
[ArgumentCompleter({ param($c, $p, $w, $a, $f) … })]
Register-ArgumentCompleter -CommandName C -ParameterName P -ScriptBlock { … }
(TabExpansion2 'C -P ' 5).CompletionMatches.CompletionText6. Pipeline input
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string[]]$Target
)
begin { $n = 0 } # params from pipeline NOT bound yet
process { foreach ($t in $Target) { $n++; $t } } # per object
end { Write-Verbose "$n done" }
Trace-Command -Name ParameterBinding -PSHost -Expression { … }7. Output types, help, splatting
[OutputType('OpsKit.Server')] # metadata only
[pscustomobject]@{ PSTypeName = 'OpsKit.Server'; Name = 'web-01' }
$o.PSObject.TypeNames -contains 'OpsKit.Server'
Update-TypeData -TypeName OpsKit.Server -DefaultDisplayPropertySet Name, Env, IP
param([PSTypeName('OpsKit.Server')] $Server)
<# .SYNOPSIS … #> # top of body, or ≤ 1 blank line above function
$p = @{ Env = 'prod'; Role = 'web' }; Get-OpsServer @p -Role api
Inner @PSBoundParameters; $null = $PSBoundParameters.Remove('X')
Get-Verb -Verb Fetch # nothing → unapproved8. OpsKit v0.1
. ~/pslab/OpsKit/OpsKit.ps1 Get-OpsServer -Env prod -Role web Get-OpsConfig -Env prod; (Get-OpsConfig -All).Health $l = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080); $l.Start() Test-OpsEndpoint 127.0.0.1 18080 Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 | Group-Object Result $l.Stop() ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1; $LASTEXITCODE
Integrated lab + final quiz
Get-OpsServer -Env prod | Test-OpsEndpoint plus a local endpoint — and prove it with ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1, an acceptance script with 13 checks and exit codesScenario
Your team wants a quick “are the prod endpoints reachable?” report and a guarantee that the OpsKit functions keep their contract while you refactor them in the next lessons. You will (1) run an end-to-end report that mixes the prod inventory with a local mock endpoint and saves JSON, and (2) write an acceptance script that loads OpsKit, checks inventory counts, types, configuration, validation, unknown-parameter rejection and pipeline binding, then exits 0 (all pass) or 1 (any failure) — the same contract as Lesson 1's Test-LabData.ps1, now built from advanced functions.
. ~/pslab/OpsKit/OpsKit.ps1
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
$targets = @(Get-OpsServer -Env prod) + [pscustomobject]@{ Name = 'local-mock'; IP = '127.0.0.1'; Port = 18080 }
$report = $targets | Test-OpsEndpoint -TimeoutMs 300
$listener.Stop()
$report | Format-Table Name, Target, Port, Open, Result, Ms -AutoSize
$report | Group-Object Result -NoElement | Format-Table Count, Name -AutoSize
$report | ConvertTo-Json -Depth 2 | Set-Content ~/pslab/tmp/endpoints.json
(Get-Content ~/pslab/tmp/endpoints.json -Raw | ConvertFrom-Json).Count
Name Target Port Open Result Ms
---- ------ ---- ---- ------ --
web-01 10.30.1.41 8080 False Timeout 300
web-02 10.30.1.42 8080 False Timeout 325
api-01 10.30.1.43 8080 False Timeout 324
edge-01 10.30.2.51 8080 False Timeout 309
db-01 10.30.1.44 8080 False Timeout 311
bastion-01 10.30.2.10 8080 False Timeout 311
local-mock 127.0.0.1 18080 True Open 0
Count Name
----- ----
1 Open
6 Timeout
7
@(…) + [pscustomobject]… mixes two object shapes in one pipeline; both bind because -Target has the alias IP and Port/Name bind by property name. The listener is stopped right after the test — the report is already in $report.
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1:
<#
.SYNOPSIS
Acceptance checks for OpsKit v0.1 (Lesson 3). Lesson 8 replaces them with Pester tests.
.DESCRIPTION
Loads OpsKit by dot-sourcing OpsKit.ps1, then checks the inventory, the configuration,
parameter validation, pipeline binding and a real TCP test against a local listener.
Exit codes: 0 all checks passed; 1 at least one check failed.
.EXAMPLE
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Format-Table
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
[ValidateRange(1024, 65535)]
[int]$LocalPort = 18080
)
. (Join-Path $PSScriptRoot '..' 'OpsKit.ps1')
function New-Check {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)] [string]$Name,
[Parameter(Mandatory, Position = 1)] [AllowEmptyString()] [string]$Expected,
[Parameter(Mandatory, Position = 2)] [AllowEmptyString()] [AllowNull()] [string]$Actual
)
[pscustomobject]@{
PSTypeName = 'OpsKit.Check'
Check = $Name
Expected = $Expected
Actual = $Actual
Passed = $Expected -eq $Actual
}
}
function Get-ErrorId {
# Runs a script block and returns the FullyQualifiedErrorId of the first error, or 'no error'.
param([scriptblock]$ScriptBlock)
$ErrorActionPreference = 'Stop' # local copy, inherited by the script block (Module 2)
try { $null = & $ScriptBlock; 'no error' }
catch { ($_.FullyQualifiedErrorId -split ',')[0] }
}
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, $LocalPort)
$listener.Start()
try {
$results = @(
New-Check 'all servers' 12 @(Get-OpsServer).Count
New-Check 'prod servers' 6 @(Get-OpsServer -Env prod).Count
New-Check 'prod web servers' 'web-01,web-02,edge-01' ((Get-OpsServer -Env prod -Role web).Name -join ',')
New-Check 'type name' 'OpsKit.Server' @(Get-OpsServer -Env dev)[0].PSObject.TypeNames[0]
New-Check 'Port is a number' 'Int32' @(Get-OpsServer -Env dev)[0].Port.GetType().Name
New-Check 'prod requires confirm' 'True' (Get-OpsConfig -Env prod).RequireConfirm
New-Check 'default environment' 'dev' (Get-OpsConfig).Env
New-Check 'unknown env rejected' 'ParameterArgumentValidationError' (Get-ErrorId { Get-OpsServer -Env production })
New-Check 'unknown param rejected' 'NamedParameterNotFound' (Get-ErrorId { Get-OpsServer -Environment prod })
New-Check 'port range validated' 'ParameterArgumentValidationError' (Get-ErrorId { Test-OpsEndpoint 127.0.0.1 -Port 0 })
New-Check 'local listener open' 'True' (Test-OpsEndpoint 127.0.0.1 $LocalPort).Open
New-Check 'pipeline binds IP+Port' "127.0.0.1:${LocalPort}:True" $(
$r = [pscustomobject]@{ IP = '127.0.0.1'; Port = $LocalPort } | Test-OpsEndpoint
'{0}:{1}:{2}' -f $r.Target, $r.Port, $r.Open)
New-Check 'one result per server' 6 @(Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 100).Count
)
}
finally {
$listener.Stop()
}
$results
$failed = @($results | Where-Object { -not $_.Passed })
if ($failed.Count -gt 0) {
Write-Warning "$($failed.Count) check(s) failed: $($failed.Check -join ', ')"
exit 1
}
exit 0
New-Check is now an advanced function with mandatory positional parameters — the Lesson 1 -join mistake would be rejected. Get-ErrorId sets $ErrorActionPreference = 'Stop' in its own scope; the script block it invokes inherits that preference through dynamic scope (Module 2), so any error becomes catchable, and the function returns the first part of FullyQualifiedErrorId. (Parameter-binding and validation errors would be caught even without it, because they terminate the statement.)
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Format-Table -AutoSize; "exit=$LASTEXITCODE"
Check Expected Actual Passed ----- -------- ------ ------ all servers 12 12 True prod servers 6 6 True prod web servers web-01,web-02,edge-01 web-01,web-02,edge-01 True type name OpsKit.Server OpsKit.Server True Port is a number Int32 Int32 True prod requires confirm True True True default environment dev dev True unknown env rejected ParameterArgumentValidationError ParameterArgumentValidationError True unknown param rejected NamedParameterNotFound NamedParameterNotFound True port range validated ParameterArgumentValidationError ParameterArgumentValidationError True local listener open True True True pipeline binds IP+Port 127.0.0.1:18080:True 127.0.0.1:18080:True True one result per server 6 6 True exit=0
A real bug found while writing this check: the first version read the type name with (Get-OpsServer -Env dev | Select-Object -First 1).PSObject.TypeNames[0] and failed with Selected.System.Management.Automation.PSCustomObject (Module 7, Case 1). The script now uses @(Get-OpsServer -Env dev)[0].
[Alias('IP', …)] line from Test-OpsEndpoint.ps1, rerun, then restore it.
$f = '~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1'
$orig = Get-Content $f -Raw
(Get-Content $f) -notmatch "^\s+\[Alias\('IP'" | Set-Content $f
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 2>$null | Where-Object { -not $_.Passed } | Format-Table -AutoSize; "exit=$LASTEXITCODE"
Set-Content $f -Value $orig -NoNewline # restore
WARNING: 1 check(s) failed: pipeline binds IP+Port
Check Expected Actual Passed
----- -------- ------ ------
pipeline binds IP+Port 127.0.0.1:18080:True @{IP=127.0.0.1; Port=18080}:18080:False False
exit=1
Exactly Module 6's coercion trap: without the alias, the object was converted to the text @{IP=127.0.0.1; Port=18080} and used as a host name; Port still bound by property name.
pwsh -NoProfile -NonInteractive -File ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Out-Null; "exit=$LASTEXITCODE"
exit=0
Open-ended self-check
1. Walk through what happens, step by step, for Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300.
Both commands are found as functions. Named arguments bind: -Env prod converts to string[] and passes ValidateSet; -TimeoutMs 300 converts to int and passes ValidateRange(50, 30000). The mandatory check for -Target is deferred because it accepts pipeline input. Both begin blocks run (Test-OpsEndpoint sets its counters). Get-OpsServer's end block (its body) reads the JSON and emits OpsKit.Server objects one by one; for each, the binder tries ByValue for -Target (skipped — not a string without coercion), then ByPropertyName: IP → -Target (alias), Port → -Port, Name → -Name; then process runs the bounded connect and emits a result. After the last object, end writes the verbose summary.
2. Why can the loader not be a function such as Import-OpsKit { foreach (…) { . $file } }?
Dot-sourcing inside a function defines the functions in the function's scope, which disappears when it returns. You would have to dot-source the function itself (. Import-OpsKit) or use function global:… definitions. Modules solve this properly in Lesson 4.
3. Name three things that make a function “cmdlet-quality”.
Strict binding with typed, validated parameters ([CmdletBinding()], Validate*, parameter sets); correct pipeline behaviour (process, ByPropertyName with aliases, one object out per object in); discoverability (approved verb, comment-based help with examples, [OutputType] and a PSTypeName). Also: no Write-Host/Format-* for data and diagnostics via Write-Verbose.
4. Your colleague's function returns 0 1 2 report. Where do you look first?
At method calls whose return values are not captured — typically ArrayList.Add() — and at cmdlets like New-Item. Pipe the result into ForEach-Object { $_.GetType().Name } to see what leaked (Module 1).
Sources and version notes
| Topic | Verified result | Sources (accessed 2026-11-24) |
|---|---|---|
| Function output | Uncaptured values are output; return exits; unrolling of @(), one-element arrays and List[T]; comma and -NoEnumerate; timing of $null = / [void] / Out-Null (605 / 653 / 1,202 ms for 100,000 calls on the lab machine) | about_Functions; about_Return; this lesson's runs |
| Scope | Read-through/copy-on-assign, $script: at the prompt = global, $private:, dot-sourcing scripts and functions, $using: with -Parallel, GetNewClosure() | about_Scopes; about_Remote_Variables; about_Script_Blocks |
| Advanced functions | Any [Parameter()] or [CmdletBinding()] makes a function advanced; 12 common parameters in 7.6 (incl. ProgressAction); unknown/extra arguments rejected; -Debug does not prompt | about_Functions_Advanced; about_Functions_CmdletBindingAttribute; about_CommonParameters; about_Functions_Advanced_Methods |
| Parameters | Type conversion (8080.6 → 8081, [bool] rejects strings), Mandatory with -NonInteractive, positional binding rule, switches, parameter sets and error messages | about_Functions_Advanced_Parameters; about_Parameter_Sets |
| Validation and completion | All Validate* messages reproduced; defaults not validated; re-validation on assignment; completers tested with TabExpansion2 | about_Functions_Argument_Completion; Register-ArgumentCompleter |
| Pipeline input | Missing process → last object only; ByValue-with-coercion on [string]; alias binding; Trace-Command output for a function | about_Pipelines; Trace-Command |
| Output, help, splatting | [OutputType] not enforced; PSTypeName; Select-Object -First prepends Selected.* for PSCustomObject; help placement (6 cases); explicit parameter overrides a splat; 100 approved verbs | about_Comment_Based_Help; about_Functions_OutputTypeAttribute; about_Splatting; Update-TypeData; Approved verbs |
| OpsKit v0.1 / TCP | Local TcpListener Open; refused loopback reported after ~1 s on Windows; localhost → ::1 then 127.0.0.1; 10.x Timeout; .invalid HostNotFound | TcpClient.ConnectAsync; Import-PowerShellDataFile; this lesson's runs |
Video verification notes
Only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24 are listed:
- 8 Functions and Advance functions in PowerShell — Ashish Raj (Modules 1, 4)
- PowerShell Function Scope Explained: Local, Script & Global Variables Tutorial — CodeLucky (Module 2)
- MICROSOFT Windows PowerShell – How variable scope works in functions — HardReset_Pro (Module 2)
- Introduction to PowerShell: Module 4 - Dot-Sourcing — Bryan Cafferky (Module 2)
- PowerShell CmdletBinding Tutorial - Advanced Functions Explained for Beginners — CodeLucky (Modules 3, 8)
- A Brief explanation of CmdletBinding — Info Tech Zone (Module 3)
- MICROSOFT Windows PowerShell – How to Use CmdletBinding in Functions — HardReset_Pro (Module 3)
- PowerShell Advanced Functions — Adam Driscoll (Modules 4–8)
- PowerShell Parameter Validation: ValidateSet, ValidateRange, ValidatePattern & More — CodeLucky (Module 5)
- Powershell Basics - Pipeline Parameter Binding in DETAIL — Chasse TAC (Module 6)
- From Lesson 1's verified list: Learn PowerShell in Less Than 2 Hours — K12 Engineer; PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
oEmbed verifies titles and channels only; the videos were not watched segment by segment, and the descriptions come from titles and search summaries. Most use Windows PowerShell 5.1 or early PowerShell 7; where behaviour differs (for example -Debug prompting, ErrorMessage on validation attributes), this lesson is authoritative. No verified video was found for function output semantics, comment-based help placement, PSTypeName or TCP checks with timeouts.
Voice narration notes
The “Voice” tab uses the browser's built-in Web Speech API (en-US); it needs no network access. The narration scripts and storyboards can be passed to a TTS or video tool; the courseware does not embed audio or video files.
Known limitations
- Run environment: all “Actual output (7.6.10)” blocks were produced on Windows 11 with PowerShell 7.6.10; home-folder paths were replaced with
C:\Users\labadmin\…. Commands were run statement by statement in one session, as if typed at the prompt; errors are shown in the default ConciseView. Not run on Linux or macOS: the TCP timings (refused loopback after ~1 s,localhosttrying::1first) are Windows observations; on Linux a refused connection is normally reported immediately — not verified here. - Interactive behaviour that cannot be captured in a non-interactive run — the Mandatory prompt and
!?help, pressing Tab — is described from documentation; completion was verified withTabExpansion2instead. - Timings (
Measure-Command,Mscolumns) vary between machines and runs; only ratios and orders of magnitude are meaningful. - The
Trace-Commandoutput is shortened: timestamps,DEBUG: ParameterBinding Information: 0 :prefixes and the Import-Csv/Select-Object binding lines were removed. - Production cases are composites of common incidents; the mechanisms in them were reproduced, the surrounding stories were not.
- The animations simplify binding: they omit dynamic parameters, delay-bind script blocks and the exact order of positional binding across parameter sets.