PowerShell Lesson 2: Language Essentials — Types, Operators, Collections and Control Flow

Lesson 1 showed how commands and the pipeline work; this lesson is the language you write between the commands: how values get their types and silently change them, operators that filter when you expected a true/false, regular expressions that turn log lines into objects, arrays and hashtables, switch and loops with their break/continue traps, and JSON/CSV/PSD1/XML — ending with a real access-log analyzer
PowerShell 7.6 LTS (7.6.10)Bash comparisonsLocal only · FreeVerified · 2026-11-24
Position in the Learning Path In Lesson 1 you generated the course dataset in ~/pslab/data, learned that commands emit objects, predicted pipeline parameter binding, and wrote Test-LabData.ps1 with exit codes 0/1/2. Lesson 2 is the language layer: everything you need to write correct logic inside scripts and functions. You will meet the same dataset again — access.log's 20 server errors, the six 401s at lines 151–156, the odd User-Agent on line 307, servers.csv's string-typed Monitored column and the PSD1 config. OpsKit milestone: no module yet — this hour produces ~/pslab/scripts/Get-AccessLogReport.ps1, the parsing and reporting logic that Lesson 3 will turn into the first OpsKit functions (Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint, v0.1).
Overall Learning Objectives
  • Predict a value's type and the result of implicit conversion: why "10" + 5 is 105 but 5 + "10" is 15, why [int]'3.5' is 4 and [int]2.5 is 2, and use type accelerators such as [datetime], [version], [ipaddress] and [regex].
  • Put $null on the left of comparisons, know the important automatic variables ($_/$PSItem, $?, $LASTEXITCODE, $args, $Matches) and use Set-StrictMode to catch typos.
  • Explain why an array on the left of a comparison operator filters instead of returning $true/$false — this lesson's first big idea — and choose between -like/-match, -contains/-in, and the case-sensitive -c… forms.
  • Turn a text line into an object with a named-group regular expression and $Matches — the core animation of this lesson — and use -replace (with $1, ${name} and script blocks), -split, -join, [regex]::Matches and Select-String.
  • Choose the right collection: arrays (fixed size, measured cost of +=), List[T], hashtables as lookups and counters, [ordered], member enumeration and [pscustomobject]; preview splatting.
  • Write if/elseif/else and switch (arrays, -Regex, -Wildcard, -File, break/continue) and avoid comparison pitfalls such as '200' -gt 1000.
  • Pick the right loop and reproduce the most dangerous trap of the hour: break inside ForEach-Object stops the enclosing loop or script, not the pipeline.
  • Convert structured data safely: ConvertTo-Json -Depth (the depth-2 truncation warning), ConvertFrom-Json -AsHashtable, JSON keeps types while CSV makes strings, Export-Csv -UseQuotes, Import-PowerShellDataFile and [xml].

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassBridge and warm-upCheck the dataset hashes, Lesson 1 recap questions, create ~/pslab/scripts and ~/pslab/tmpWarm-up quiz from memoryRebuild data if hashes differ
100–06Variables and typesCasting, accelerators, implicit conversion (left operand wins), banker's rounding, $null on the left, automatic variables, Set-StrictModeType conversion stepperCast fields of a log line; catch a typo with strict mode
206–13Operators-eq/-ceq/-ieq, arrays on the left, -like vs -match, -contains vs -in, logic, -f, -is/-as, ranges, ?:, ??, ??=, &&/||Operator evaluator: filter or Boolean?Status-code filtering and a config with defaults
313–21Strings and regex-match, $Matches, named groups, -replace, -split/-join, [regex]::Matches, Select-String -AllMatches, casecore animation: from a log line to an objectParse access.log line 1, 151 and 307
421–28Collections@(), fixed size, the cost of += (measured), List[T], hashtables, [ordered], counters and lookups, member enumeration, [pscustomobject], splattingWhat happens in memoryCount status codes with a hashtable; time += vs List.Add
528–35Conditionalsif as an expression, switch on values, arrays, script-block conditions, -Wildcard, -Regex, -File, break/continue, truthinessswitch evaluatorClassify every log line with switch -Regex -File
635–42Loopsforeach statement vs ForEach-Object (and the alias), for, while, do, labels, .ForEach()/.Where(), break/continue/return in script blocksWhere does break land?Reproduce a script that silently stops early
742–50Structured dataConvertTo-Json -Depth, ConvertFrom-Json -AsHashtable, JSON vs CSV types, Export-Csv -UseQuotes, PSD1, [xml]JSON / CSV round-trip simulatorCompare inventory.json and servers.csv
850–60Practice: access-log analyzerNamed-group regex → typed objects → group/measure → report object → JSONAnalyzer data flow + troubleshooting treeWrite ~/pslab/scripts/Get-AccessLogReport.ps1
—After ClassCheat sheet · Integrated labWrite the JSON summary and Test-AccessLogSummary.ps1 that validates it with exit codes 0/1/2Final quiz (12 questions)All nine checks pass; tampering is detected

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Predict types and conversions✓✓··✓·✓✓[int], [datetime], [version], -is, -as, .GetType()M1, M8
Handle $null and automatic variables✓✓✓·✓✓··$null -eq $x, $?, $LASTEXITCODE, $Matches, Set-StrictModeM1
Use comparison operators correctly·✓✓·✓··✓-eq, -ceq, -like, -match, -contains, -inM2
Parse text with regular expressions··✓·✓··✓-match, (?<name>…), -replace, -split, Select-StringM3, M8, integrated lab
Choose and use collections·✓·✓·✓✓✓@(), List[T], @{}, [ordered], [pscustomobject]M4, M8
Write conditionals·✓··✓✓·✓if, switch -Regex -File, ?:, ??M5
Write loops without surprises···✓✓✓·✓foreach, ForEach-Object, .Where(), labels, Select-Object -FirstM6
Convert JSON / CSV / PSD1 / XML···✓··✓✓ConvertTo-Json -Depth, ConvertFrom-Json -AsHashtable, Export-Csv, [xml]M7, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Functions, scopes, [CmdletBinding()], parameter validation, pipeline-aware begin/process/endTool-making builds on this lesson's languageLesson 3 (OpsKit v0.1)
Classes and enums, using namespace, advanced .NET interopNot needed for scripting; covered when building modulesLesson 4
try/catch/finally, $ErrorActionPreference, error records in depthThis lesson only uses try/catch to show messagesLesson 5
File encodings, BOMs, providers, cross-platform paths in depthEnvironment concernsLesson 4
ForEach-Object -Parallel, jobs, runspacesConcurrencyLesson 6
Invoke-RestMethod and JSON from web APIsJSON is introduced here; APIs come laterLesson 7
Regex engine theory (backtracking, lookbehind performance), full .NET regex syntaxToo broad for one hourMicrosoft Learn: .NET regular expression language reference (Sources page)

How to use these materials

10 pages per module
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Read “Principles”, predict the result before you play the “Animation”, then type the “Lab” in ~/pslab. Module 3's regex-to-object animation is the thread that leads to Module 8's analyzer.
Learning progress
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).
Voice narration
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.
Version notes Verified 2026-11-24 on PowerShell 7.6.10 (.NET 10.0.15, Windows). Language features used here and their minimum versions: ternary ?:, ??, ??=, ?. and the pipeline chain operators &&/|| need PowerShell 7.0+; Export-Csv -UseQuotes and ConvertFrom-Json -AsHashtable need 7.0+ (6.0+ for -AsHashtable); ConvertFrom-Json -DateKind needs 7.5+. Windows PowerShell 5.1 has none of these operators, writes #TYPE lines in Export-Csv unless you pass -NoTypeInformation, and its ConvertFrom-Json returns an array as one object. Hashtable key order is not stable even between two runs of pwsh 7 (.NET randomizes string hashing per process) — this lesson shows the evidence.

Module 0 · Bridge and warm-up (sample dataset, Lesson 1 recap)

Confirm that ~/pslab/data is intact, refresh the Lesson 1 ideas this lesson builds on, and prepare the folders for this hour's scripts
Before class ≈ 5 minRuns locally · FreeWrites only inside ~/pslab
Prerequisites
  • Lesson 1 completed, or at least its Module 0: PowerShell 7.6 installed, ~/pslab/New-LabData.ps1 saved and ~/pslab/data generated.
  • VS Code with the PowerShell extension (recommended). Every example in this lesson is typed at a pwsh prompt whose current location is ~/pslab unless stated otherwise.
  • Familiarity with regular expressions from grep -E in the Bash course helps in Module 3, but is not required.

Check the dataset

Set-Location ~/pslab
Get-ChildItem ./data -File | Get-FileHash |
    ForEach-Object { '{0}  {1}' -f $_.Hash.Substring(0, 16), (Split-Path $_.Path -Leaf) }
(Get-Content ./data/access.log).Count
A0A0D5B9D3B4C974  access.log
6E3808C1DB0D3276  inventory.json
381E684642929B30  opskit.config.psd1
6323C180C2EFF12E  servers.csv
611

If any prefix differs, rebuild with ./New-LabData.ps1 (it only deletes and recreates ~/pslab/data). Every “Actual output” in this lesson assumes these exact files.

Warm-up: answer from memory (30 seconds)

1. What type is the Monitored column after Import-Csv ./data/servers.csv, and what does [bool]'false' return?

A string ("true"/"false"), and $true — every non-empty string is truthy. Module 1 and Module 7 explain the rule and the fix.

2. Which binds first when an object comes down the pipeline: ByValue or ByPropertyName?

ByValue. The full order is ByValue → ByPropertyName without type coercion, then ByValue → ByPropertyName with coercion. Today's operators and loops work on the same objects.

3. "Items: $n.Count" — what is printed if $n = 3,5,8?

Items: 3 5 8.Count. Only the variable is expanded; use $($n.Count). Module 3 adds -f as a cleaner alternative.

4. How many 5xx lines does access.log contain, and on which path?

20 (500×8, 502×4, 503×8), all on /api/orders. Module 8's analyzer must report exactly that.

5. What exit code does Test-LabData.ps1 return when the data folder is missing?

2 (1 = a check failed, 0 = all passed). The integrated lab of this lesson uses the same convention for Test-AccessLogSummary.ps1.

Bridge: what Lesson 1 gave you and what Lesson 2 adds

Lesson 1 (commands)Lesson 2 (language)
Where-Object Status -ge 500 filters objects in a pipeline$codes -ge 500 filters an array without a pipeline — and surprises you inside if (Module 2)
Select-String '" 5\d\d ' finds lines-match with named groups extracts fields into objects (Module 3)
Group-Object countsA hashtable counter does the same in one pass, and is a lookup table too (Module 4)
Import-Csv returns stringsConvertFrom-Json keeps numbers and booleans (Module 7)
A script with param() and exit codesA script with real logic: parse → aggregate → report → JSON (Module 8)

Prepare the folders for this hour

'scripts', 'tmp' | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path ~/pslab $_) -Force } | Out-Null
Get-ChildItem ~/pslab -Directory -Name
data
scripts
tmp

Environment self-check checklist

Risks and cleanup This lesson writes only to ~/pslab/scripts and ~/pslab/tmp; one Module 7 step deliberately writes an unsafe .psd1 to tmp to show that Import-PowerShellDataFile refuses to run code. Never run Invoke-Expression or dot-source a data file you received from someone else. Clean up at any time with Remove-Item ~/pslab/tmp/* -Recurse; ~/pslab/scripts/Get-AccessLogReport.ps1 is kept for Lesson 3.

Module 1 · Variables and the type system: casting, type accelerators, $null, automatic variables

00:00 – 06:00 · Every value in PowerShell is a .NET object with a type; operators convert the right operand to the type of the left one, casts convert explicitly, and $null behaves differently depending on which side of a comparison it is on
6 min[int] · [datetime] · [version] · $null★★★★★
Learning objectives
  • Create variables, read their type with .GetType(), and type-constrain a variable ([int]$n = '7') so later assignments are converted or rejected.
  • Use type accelerators — [int], [long], [double], [datetime], [version], [ipaddress], [regex] — to parse text into real values, and know that [int] rounds half to even.
  • Predict implicit conversion: the left operand decides the operation ("10" + 5 → 105, 5 + "10" → 15).
  • Always write $null -eq $x, and use the automatic variables $_/$PSItem, $?, $LASTEXITCODE, $args and $Matches correctly.
  • Turn on Set-StrictMode -Version Latest in scripts to make typos and missing properties fail loudly.
Prerequisites: Module 0. Importance:★★★★★ (half of all “the script runs but the numbers are wrong” bugs are silent type conversions)

What: variables hold .NET objects

A variable is a name in the current scope ($name; names are case-insensitive, so $serverName and $servername are the same variable). It is created on first assignment and can hold any object. Unless you constrain it, it takes the type of whatever you assign last. Literal types follow simple rules:

LiteralType (verified on 7.6.10)Note
42System.Int32Grows to Int64 automatically: 2147483648 is Int64
4.2DoubleUse 4.2d for Decimal (money)
1kb, 10gbInt32, Int64Multipliers kb, mb, gb, tb, pb (powers of 1024)
'text', "text $x"StringSingle quotes literal, double quotes expand (Lesson 1, Module 7)
$true, $false, $nullBoolean, —$null has no type; calling .GetType() on it fails
1, 2, 3 / @()Object[]The comma operator builds arrays (Module 4)
@{ a = 1 }Hashtable[ordered]@{…} is an OrderedDictionary

Why: conversions happen everywhere

PowerShell tries hard to make values fit. That is convenient interactively and dangerous in scripts. The rule that explains most surprises: for binary operators, the type of the left operand decides the operation, and the right operand is converted to it. "10" + 5 is string concatenation (105); 5 + "10" is addition (15); "10" * 3 repeats the string (101010). The same rule makes 5 -eq "5.0" true (numeric) but "5.0" -eq 5 false (string comparison of "5.0" and "5"). In Bash everything is a string until an arithmetic context $(( )) says otherwise; in PowerShell everything has a type and the left side chooses.

How: casts and type accelerators

AcceleratorFull typeTypical use on the course data
[int], [long]Int32, Int64HTTP status ([int]'503'), byte counts ([long]'48213'). [int]'3.5' is 4 and [int]2.5 is 2: banker's rounding (to even)
[datetime]System.DateTimeCasts use the invariant culture ('2026-11-24 10:00:01'); for the nginx format use [datetime]::ParseExact() (Module 3)
[version]System.VersionCompare versions: [version]'7.6.10' -gt [version]'7.10.0' is False, but as strings it is True
[ipaddress]System.Net.IPAddressValidate servers.csv IPs: '10.30.1.41' -as [ipaddress]
[regex]System.Text.RegularExpressions.RegexA compiled pattern with .Match(), .Matches(), .Replace()
[bool]System.Boolean[bool]'false' is $true; use [bool]::Parse('false') or compare to 'true'
[pscustomobject], [ordered]—Only valid in front of a hashtable literal (Module 4)

A type-constrained variable keeps its type: after [int]$n = '7', the assignment $n = '8' stores the integer 8, and $n = 'eight' throws. This is a cheap safety net in scripts.

When: $null on the left, automatic variables and strict mode

$null: when the left operand is a collection, a comparison filters (Module 2). So $a -eq $null returns the null elements of $a, which may be truthy, falsy or empty. $null -eq $a always returns a single Boolean. PSScriptAnalyzer flags the wrong order (rule PossibleIncorrectComparisonWithNull, Lesson 8).

Automatic variableMeaningTrap
$_ / $PSItemCurrent pipeline object in script blocks (Where-Object, ForEach-Object, switch, catch)Means something different inside a nested script block
$?Did the last command succeed? (Boolean)Overwritten by every command, including Write-Host
$LASTEXITCODEExit code of the last native program or script that called exitNot changed by cmdlets
$argsUnbound arguments of a function/script without param()Prefer param() (Lesson 3)
$MatchesHashtable of groups from the last successful scalar -matchNot cleared on failure (Module 3)
$PSScriptRoot, $HOME, $PWD, $PSVersionTableScript folder, home, location, versionLesson 1

Set-StrictMode -Version Latest turns silent mistakes into errors: reading a variable that was never assigned, reading a property that does not exist, calling a function like a method f(1,2), and out-of-range array indexes. It applies to the scope where you set it and its children — put it at the top of scripts, not in your profile.

Common misconceptions① “[int] truncates like C” — it rounds half to even: [int]2.5 is 2, [int]3.5 is 4; use [math]::Floor() or [math]::Truncate(). ② “'5.0' -eq 5 is true” — the left operand is a string, so 5 becomes "5": false. ③ “if ($list -eq $null) checks for null” — it filters the list. ④ “[bool]'false' is false” — any non-empty string is true. ⑤ “Variable names are case-sensitive like Bash” — they are not; $Path and $path are the same variable. ⑥ “$? holds the exit code” — it is a Boolean; the code is in $LASTEXITCODE.

Diagram: the left operand decides

left OP right Left is a Stringright → String"10" + 5 → "105""5.0" -eq 5 → False Left is a numberright → number (or error)5 + "10" → 155 + "abc" → error Left is a collectioncomparison filters elements@(1,$null,2) -eq $null → $null+ appends: @(1,2) + 3 → 1,2,3 Explicit casts override the rule: [int]"10" + 5 → 15 · [string]5 + "10" → "510" $null on the left always gives one Boolean: $null -eq $x Typed variables convert on every assignment: [int]$n = '7' → 7; $n = 'eight' → error
Figure 1-1: the left operand's type chooses string, numeric or collection semantics

Diagram: where values get their types

Text sourcesGet-Content, Import-Csvnative programs → String Typed sourcescmdlets, ConvertFrom-JsonInt64, Boolean, DateTime Your casts[int] [datetime] [version][ipaddress] ParseExact() Operatorsimplicit conversionleft operand wins Rule of thumb for scripts: convert text to real types once, at the edge (when you parse),then compare and calculate on typed values — never on strings that only look like numbers or dates.
Figure 1-2: parse at the edge, compute on types (Module 8's analyzer follows this rule)

Type conversion stepper

Pick an expression and step through how PowerShell decides its type and result. Every result was reproduced on 7.6.10.

Ready.
Real mechanism behind the animation The PowerShell binder looks at the runtime type of the left operand and picks the operation (string concatenation, numeric addition, array concatenation, comparison). It then converts the right operand with PowerShell's conversion rules (LanguagePrimitives.ConvertTo): parsing strings with the invariant culture, IConvertible, constructors and static Parse methods. Comparisons with a collection on the left are applied to each element.

Command table

Command / syntaxPurposeNotes
$x.GetType().FullNameExact type of a valueFails on $null; use $null -eq $x first
[int]$n = '7'Type-constrained variableConverts every later assignment
[datetime]::ParseExact(s, fmt, [cultureinfo]::InvariantCulture)Parse a fixed date formatCulture-independent
$x -is [int] / $x -as [int]Test / try-convert-as returns $null instead of throwing (Module 2)
Get-Variable, Remove-VariableInspect / delete variablesGet-Variable -Scope Script
Set-StrictMode -Version LatestFail on unset variables and missing propertiesPer scope; put at the top of scripts
[System.Management.Automation.PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::GetList all type acceleratorsLong, but complete
Set-Location ~/pslab
[int]'42' + 1
[int]'3.5'
[int]2.5; [int]3.5
[datetime]'2026-11-24 10:00:01'
[version]'7.6.10' -gt [version]'7.10.0'
'7.6.10' -gt '7.10.0'
[ipaddress]'198.51.100.23' | Format-List IPAddressToString, AddressFamily
([regex]'" (\d{3}) ').Match((Get-Content ./data/access.log -TotalCount 1)).Groups[1].Value
43
4
2
4

Tuesday, November 24, 2026 10:00:01 AM
False
True

IPAddressToString : 198.51.100.23
AddressFamily     : InterNetwork

200

How to verify: the version comparison is the classic one: as strings '7.6.10' -gt '7.10.0' compares character by character and '6' > '1', so it is True — wrong. Common mistake: sorting version folders or module versions as strings. Production use: Sort-Object { [version]$_.Name } for version-named folders.

"10" + 5
5 + "10"
"10" * 3
3 * "10"
5 -eq "5.0"
"5.0" -eq 5
@(1,2) + 3
'1,2' + 3
105
15
101010
30
True
False
1
2
3
1,23

$null on the left

$a = @(1, $null, 2, $null)
($a -eq $null).Count
if ($a -eq $null) { 'right: null?!' } else { 'right: not null' }
if ($null -eq $a) { 'left: null' } else { 'left: not null' }
$e = @()
if ($e -eq $null) { 'empty, right: null' } else { 'empty, right: not null?!' }
2
right: null?!
left: not null
empty, right: not null?!

With $null on the right, a two-element result (two nulls) is truthy, and an empty array gives an empty result, which is falsy — the answer depends on the data, not on the question. With $null on the left the answer is always one Boolean.

Automatic variables

Get-Item ./data/nope.txt -ErrorAction SilentlyContinue; "`$? = $?"
cmd /c exit 3; "LASTEXITCODE = $LASTEXITCODE, `$? = $?"      # Linux/macOS: sh -c 'exit 3'
'GET /healthz' -match '^(?<method>\S+) (?<path>\S+)' | Out-Null; $Matches
1..2 | ForEach-Object { "$_ / $PSItem" }
function Show-Args { "count=$($args.Count) first=$($args[0])" }
Show-Args alpha beta
$? = False
LASTEXITCODE = 3, $? = False

Name                           Value
----                           -----
method                         GET
path                           /healthz
0                              GET /healthz
1 / 1
2 / 2
count=2 first=alpha

Strict mode catches typos

$serverName = 'web-01'
"[$ServerNmae]"                        # typo: silently empty
Set-StrictMode -Version Latest
"Server: $servername"                  # names are case-insensitive: fine
$ServerNmae
[]
Server: web-01
InvalidOperation: The variable '$ServerNmae' cannot be retrieved because it has not been set.

Goal: Convert the text fields of a log line into real types and see what goes wrong without conversion. Environment: pwsh 7.6 in ~/pslab. Cost: none; nothing is written to disk.

Split line 1 into fields (a naive split, improved in Module 3):
Set-Location ~/pslab
$f = (Get-Content ./data/access.log -TotalCount 1) -split ' '
$f[0], $f[8], $f[9]
$f[8].GetType().Name
203.0.113.7
200
2
String
Compare as strings vs as numbers: '200' -gt 1000 is a string comparison because the left side is a string.
$f[8] -gt 1000
[int]$f[8] -gt 1000
1000 -lt $f[8]
True
False
False

Putting the number on the left (or casting) gives the numeric answer. Module 5 shows this bug inside an if.

Validate the IP addresses in servers.csv with -as [ipaddress]:
Import-Csv ./data/servers.csv | Where-Object { -not ($_.IP -as [ipaddress]) } | Measure-Object | Select-Object -ExpandProperty Count
'10.30.1.999' -as [ipaddress]
$null -eq ('10.30.1.999' -as [ipaddress])
0
True

All 12 IPs are valid; the invalid one converts to $null (nothing printed) instead of throwing.

Type-constrain a variable:
[int]$status = '503'; $status.GetType().Name
$status = '404'; $status.GetType().Name
try { $status = 'Not Found' } catch { $_.Exception.Message }
Int32
Int32
Cannot convert value "Not Found" to type "System.Int32". Error: "The input string 'Not Found' was not in a correct format."
Cleanup: Remove-Variable f, status -ErrorAction Ignore; Set-StrictMode -Off (or simply close the session).

Case 1: the “newest” module version was the oldest

Problem: A deployment script picked the newest version folder of an internal module with Get-ChildItem $root | Sort-Object Name -Descending | Select-Object -First 1. After version 1.10.0 was published, servers kept loading 1.9.3. Root cause: folder names are strings; '1.9.3' -gt '1.10.0' because '9' > '1'. Fix: Sort-Object { [version]$_.Name } -Descending, and test with a two-digit minor version.

Case 2: a byte counter that concatenated

Problem: A report summed the Bytes column of a CSV with $total = $row.Bytes; foreach (…) { $total += $row.Bytes } and printed a 40-digit number. Root cause: the first value was a string from Import-Csv, so += concatenated strings. Fix: start with a typed accumulator ([long]$total = 0) or use Measure-Object Bytes -Sum; convert at the edge.

Case 3: “if ($servers -eq $null)” skipped the alert

Problem: A monitoring script tested whether an API returned nothing with if ($result -eq $null) { Send-Alert }. When the API returned an empty array, no alert was sent. Root cause: with a collection on the left, -eq filters; an empty array produces an empty (falsy) result. Fix: if ($null -eq $result -or @($result).Count -eq 0); enable PSScriptAnalyzer in CI (Lesson 8).

Common errors and fixes

Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format."

Cause: a cast, a typed variable or a numeric left operand met a non-numeric string (5 + "abc").

'abc' -as [int]          # $null instead of an error
[int]::TryParse('abc', [ref]$null)

Fix: validate with -as or TryParse before converting; count and report bad rows instead of failing on the first one.

You cannot call a method on a null-valued expression.

Cause: the variable is $null — often a typo, a property that does not exist, or a command that returned nothing.

Set-StrictMode -Version Latest   # now the typo itself is reported
$null -eq $x

Fix: check for $null first or use the null-conditional ${x}?.Method() (Module 2).

The variable '$x' cannot be retrieved because it has not been set.

Cause: strict mode is on and the variable was never assigned (typo or wrong scope).

Fix: correct the name, or initialize it ($x = $null) before conditional assignment.

A date compares wrongly or shows the wrong day

Cause: comparing date strings, or parsing with the current culture (Get-Date '03/04/2026' is March 4 in en-US, 3 April in en-GB).

[datetime]::ParseExact('24/Nov/2026:10:00:01 +0000', 'dd/MMM/yyyy:HH:mm:ss zzz', [cultureinfo]::InvariantCulture)

Fix: parse with an explicit format and the invariant culture; store and compare UTC (.ToUniversalTime()).

Command-line exercises
1. Print the types of 42, 2147483648, 4.2 and 1gb in one line.
(42, 2147483648, 4.2, 1gb | ForEach-Object { $_.GetType().Name }) -join ', '

Int32, Int64, Double, Int32 (1gb = 1073741824 still fits in Int32; 10gb does not).

2. Count the rows of servers.csv whose Monitored value really means true, without using string comparison.
(Import-Csv ~/pslab/data/servers.csv | Where-Object { [bool]::Parse($_.Monitored) }).Count

8. [bool]::Parse accepts true/false in any case and throws on anything else — which is what you want for data validation.

Scenario analysis
A colleague's script computes disk usage as $used = $disk.Size - $disk.Free from a CSV and reports “Cannot convert value … to type System.Int64” for one server and absurd values for others. Analyze.

CSV values are strings. "500" - "120" works because - has no string meaning, so PowerShell converts both to numbers — that hides the problem until a row has an empty value or a unit such as "500GB", which fails, and an empty string becomes 0, giving absurd results. Fix: convert at the edge with validation — $size = $row.Size -as [long]; if ($null -eq $size) { Write-Warning "bad Size for $($row.Name)"; continue } — and do the arithmetic on typed values. Add Set-StrictMode -Version Latest to catch misspelled column names.

Verified teaching videos

▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
English · variables, types and scripting basics
▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · objects and types as a foundation

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: “10” + 5 and 5 + “10” side by side; the left operand glows and pulls the right one into its type.
Narration: in PowerShell, the left side decides. A string on the left means string rules.
Shot 2 · 20–45s
Visual: the text “503” passes through an [int] gate and becomes a number; “7.10.0” passes through [version].
Narration: convert text to real types once, at the edge, with casts and type accelerators.
Shot 3 · 45–70s
Visual: an array with two nulls on the left of -eq produces two nulls — the if statement turns green; with $null on the left one False appears.
Narration: always put $null on the left.
Shot 4 · 70–90s
Visual: a typo $ServerNmae silently prints nothing; Set-StrictMode turns it into a red error.
Narration: strict mode makes silent mistakes loud. Put it at the top of every script.
or score ≥ 70% on the Quiz

Module 2 · Operators: comparison and case, arrays on the left, -like / -match, -contains / -in, -f

06:00 – 13:00 · Comparison operators are case-insensitive by default and act as filters when the left operand is a collection; choosing between wildcard, regex and membership operators is the difference between a correct and a silently wrong condition
7 min-eq · -like · -match · -contains · ?? · &&★★★★★
Learning objectives
  • Use -eq, -ne, -gt, -ge, -lt, -le and their case-sensitive (-ceq) and explicit case-insensitive (-ieq) forms.
  • Explain and use the array-on-the-left behavior: a comparison returns the matching elements, not a Boolean.
  • Choose between -like (wildcard, whole string), -match (regex, anywhere), -contains/-in (exact membership in a collection).
  • Combine conditions with -and, -or, -not/!, -xor; format output with -f; test and convert with -is/-as; build ranges with ...
  • Use the PowerShell 7 operators: ternary ?:, null-coalescing ?? and ??=, null-conditional ?., and the pipeline chain operators &&/||.
Prerequisites: Module 1. Importance:★★★★★

What: the operator families

FamilyOperatorsReturns (scalar left)Returns (collection left)
Equality / ordering-eq -ne -gt -ge -lt -leBooleanMatching elements
Wildcard-like -notlikeBooleanMatching elements
Regex-match -notmatchBoolean + sets $MatchesMatching elements; $Matches not set
Membership-contains -notcontains (collection left), -in -notin (collection right)Boolean, always — exact equality, no wildcards
Type-is -isnot -asBoolean / converted value or $null
Logical-and -or -xor -not !Boolean; -and/-or short-circuit
Format / range / split / join / replace-f .. -split -join -replaceString, array (Module 3)
PowerShell 7?: ?? ??= ?. ?[] && ||Value; chain operators act on success ($?)

Every string comparison operator is case-insensitive by default ('PROD' -eq 'prod' is True). Add c for case-sensitive (-ceq, -clike, -cmatch, -ccontains, -creplace) or i to say “insensitive” explicitly. Bash's [[ $a == $b ]] is case-sensitive — the opposite default.

Why: a collection on the left filters

When the left operand is a collection, the operator is applied to each element and the elements that pass are returned: 200,404,500,503 -ge 500 returns 500, 503. This is useful (fast filtering without a pipeline) and dangerous inside if, because the result is then judged by truthiness: an empty result is false, one element is judged by its own value (@(0) -eq 0 → 0 → false!), and two or more elements are always true.

How: choose the right matching operator

QuestionOperatorExample on the course data
Does the whole string fit a simple pattern?-like with * ? [ ]$s.Name -like 'web-*'
Does a regex match anywhere in the string?-match$line -match '" 5\d\d ' — anchor with ^ $ when you mean the whole string
Is this exact value in a list?-contains / -in'api' -in ($s.Role -split ',') — for edge-01's "web,api"
Is it a substring?-like '*x*' or .Contains('x').Contains() is case-sensitive

When: PowerShell 7 operators

OperatorMeaningExample
c ? a : bTernary$count -gt 0 ? 'ALERT' : 'OK'
a ?? ba unless it is $null (empty strings and 0 count as values)$cfg.LogLevel ?? 'Information'
$a ??= bAssign only if $nullDefaults for missing config keys
${a}?.Prop, ${a}?[0]Member access only if not $nullBraces required: $a?.Prop reads a variable named a?
cmd1 && cmd2, cmd1 || cmd2Run cmd2 if cmd1 succeeded / failed ($?; for native programs the exit code)git pull && ./build.ps1 — same meaning as in Bash
Common misconceptions① “-contains searches inside a string” — 'web,api' -contains 'api' is False; it tests collection membership. ② “-like 'web' matches web-01” — -like must match the whole string; you need 'web*'. ③ “-match '.txt' means ends with .txt” — the dot is any character and the pattern is unanchored: 'atxt' -match '.txt' is True. ④ “if ($codes -eq 404) asks whether all codes are 404” — it asks whether any element equals 404 (and returns them). ⑤ “$x?.Length is null-safe” — without braces it reads the variable x?; verified on 7.6.10: $s = $null; "$($s?.Length)" prints 0. ⑥ “?? treats empty strings as missing” — only $null is missing.

Diagram: scalar vs collection on the left

404 -eq 404scalar on the left Trueone Boolean 200,404,500,503 -ge 500collection on the left 500, 503the elements that pass Inside if ( … ) the result is judged by truthiness 0 elements → false 1 element → that element: @(0) -eq 0 → 0 → false! 2+ elements → true: @(0,0) -eq 0 → true -contains / -in always return one Boolean $null -eq $x always returns one Boolean Same for -ne -gt -lt -like -match (-match on a collection does not set $Matches)
Figure 2-1: an array on the left turns a comparison into a filter — this module's key idea

Diagram: which matching operator?

What do you compare? Exact value-eq / -ceq'PROD' -eq 'prod' → True Simple pattern-like 'web-*'whole string, * ? [ ] Regex-match '^web-\d+$'anywhere unless anchored Membership-contains / -inexact element, Boolean
Figure 2-2: equality, wildcard, regex or membership — four different questions

Operator evaluator: filter or Boolean?

Choose an expression, predict the result, then step through it. Each final result is the real output from PowerShell 7.6.10.

Ready.

Command reference

SyntaxPurposeNotes
$a -eq $b, -ceq, -ieqEquality (default / case-sensitive / explicit insensitive)Same pattern for all string operators
$array -ge 500Filter without a pipelineFaster than Where-Object for in-memory arrays
-like 'web-*' / -match '^web-\d+$'Wildcard / regex test-match sets $Matches (scalar only)
$list -contains $x / $x -in $listMembershipExact; -ccontains for case
'{0,-10}{1,6:N0}' -f $a, $bFormat: alignment, number and date formats.NET composite formatting
$x -is [int], $x -as [int]Type test / safe conversion-as → $null on failure
1..5, 'a'..'e', $lines[150..155]Ranges and slicesInclusive on both ends
c ? a : b, ??, ??=, ${x}?.PPowerShell 7 conditional and null operatorsNot in 5.1
a && b, a || bPipeline chain operatorsBased on $?
$codes = 200, 404, 500, 503, 200
$codes -eq 200
$codes -ge 500
($codes -ne 200).Count
if ($codes -eq 404) { 'contains a 404 (by accident)' }
if (@(0) -eq 0) { 'truthy' } else { '@(0) -eq 0 returns @(0), which is falsy' }
if (@(0,0) -eq 0) { '@(0,0) -eq 0 returns two zeros: truthy' }
200
200
500
503
3
contains a 404 (by accident)
@(0) -eq 0 returns @(0), which is falsy
@(0,0) -eq 0 returns two zeros: truthy

How to verify: wrap the expression in @( … ).Count to see how many elements came back. Common mistake: using a collection comparison as a condition. Production use: state the intent — $codes -contains 404 (membership), @($codes -ge 500).Count -gt 0 (any), @($codes -lt 500).Count -eq $codes.Count (all).

'web-01' -like 'web'
'web-01' -match 'web'
'edge-01', 'web-01', 'web-02' -like 'web*'
'atxt' -match '.txt'
'web,api' -contains 'api'
('web,api' -split ',') -contains 'api'
'api' -in 'web', 'api', 'db'
'web', 'api' -contains 'API'; 'web', 'api' -ccontains 'API'
False
True
web-01
web-02
True
False
True
True
True
False
'{0,-10}|{1,6}|{2:N0}' -f 'web-01', 72, 2918056
'{0:P1}' -f (20 / 611)
'{0:yyyy-MM-dd HH:mm}' -f [datetime]'2026-11-24 10:29:50'
'42' -is [string]; ('42' -as [int]) -is [int]
$null -eq ('abc' -as [int])
$lines = Get-Content ./data/access.log
($lines[150..155] | ForEach-Object { ($_ -split ' ')[8] }) -join ','
web-01    |    72|2,918,056
3.3%
2026-11-24 10:29
True
True
True
401,401,401,401,401,401

Array indexes start at 0, so file lines 151–156 are $lines[150..155]. The N0 and P1 formats use the current culture's separators.

PowerShell 7 operators

$count = @(Get-Content ./data/access.log) -match '" 5\d\d ' | Measure-Object | Select-Object -ExpandProperty Count
$count -gt 0 ? "ALERT: $count server errors" : 'OK'
$cfg = @{ LogLevel = $null; Region = 'canadacentral' }
$cfg.LogLevel ?? 'Information'
$cfg.Timeout ??= 5; $cfg.Timeout
$cfg.Timeout ??= 30; $cfg.Timeout
$s = $null
"[$($s?.Length)] [$(${s}?.Length)]"
Test-Path ./data/servers.csv && 'found'
Get-Item ./data/nope -ErrorAction SilentlyContinue || 'fallback ran'
cmd /c exit 1 || "native failed with $LASTEXITCODE"
ALERT: 20 server errors
Information
5
5
[0] []
True
found
fallback ran
native failed with 1

[0]: without braces, $s?.Length reads the undefined variable s?, and $null.Length is 0. ${s}?.Length is the real null-conditional access and returns $null. Note also that Test-Path returned True and && ran: the chain operator looks at success, not at the value — Test-Path ./nope && 'x' still runs 'x', because Test-Path succeeded in answering False.

Goal: Filter the access log's status codes with operators only, then write a config reader with defaults. Environment: pwsh 7.6 in ~/pslab. Cost: none.

Extract every status code into an int array:
Set-Location ~/pslab
$status = foreach ($l in Get-Content ./data/access.log) { [int](($l -split '"')[2].Trim() -split ' ')[0] }
$status.Count; ($status -ge 500).Count; ($status -eq 401).Count
611
20
6

Splitting on " first isolates the part after the request (' 200 2 '), which keeps working even if a request or a referrer ever contains a space. Module 3 replaces this with one regex.

Any / all / none — write the intent explicitly:
'any 5xx:  {0}' -f (@($status -ge 500).Count -gt 0)
'all <600: {0}' -f (@($status -ge 600).Count -eq 0)
'has 418:  {0}' -f ($status -contains 418)
any 5xx:  True
all <600: True
has 418:  False
Wildcard vs regex vs membership on servers.csv:
$servers = Import-Csv ./data/servers.csv
($servers | Where-Object Name -like 'web-*').Count
($servers | Where-Object Name -match '^(web|api)-0[12]$').Count
($servers | Where-Object { 'api' -in ($_.Role -split ',') }).Name -join ','
($servers | Where-Object Role -eq 'api').Name -join ','
4
7
api-01,api-01,api-01,edge-01
api-01,api-01,api-01

Only the membership test finds edge-01, whose role is "web,api".

Defaults with ??=: read the PSD1 config and fill in missing values.
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
$cfg.Health.TimeoutSec ??= 30          # exists: unchanged
$cfg.Health.UserAgent  ??= 'OpsKit/0.1' # missing: added
'{0}s, {1}, LogLevel={2}' -f $cfg.Health.TimeoutSec, $cfg.Health.UserAgent, ($cfg.LogLevel ?? 'Information')
5s, OpsKit/0.1, LogLevel=Information
Cleanup: nothing was written. Remove-Variable status, servers, cfg if you like.

Case 1: a health gate that passed with failures

Problem: A release pipeline collected HTTP status codes from five endpoints and gated with if ($codes -ne 200) { throw 'unhealthy' }. A release went out while one endpoint returned 0 (connection refused, recorded as 0). Root cause: $codes -ne 200 returned @(0), a single falsy element, so the if did not fire. With two failures it would have fired. Fix: if (@($codes -ne 200).Count -gt 0) — and a unit test with exactly one failing value (Lesson 8).

Case 2: “prod” vs “Prod” in a case-sensitive store

Problem: A script selected resources with -eq 'prod', then passed the value to an API that is case-sensitive; tagging with Prod created a second environment. Root cause: PowerShell comparisons are case-insensitive, the target system is not. Fix: normalize at the edge (.ToLowerInvariant()) and use -ceq when you validate values that leave PowerShell.

Case 3: -contains on a string of roles

Problem: An inventory report showed no API servers in prod even though edge-01 served the API. Root cause: $s.Role -contains 'api' on the string "web,api" — a string is a single element, so membership tests the whole string. Fix: split first: 'api' -in ($s.Role -split ','); better, store multi-valued data as arrays (JSON, Module 7).

Common errors and fixes

An if statement fires (or does not) depending on the data

Cause: a collection on the left of a comparison.

@($codes -ne 200).Count     # how many elements came back?

Fix: use -contains/-in for membership, .Count for any/all, and $null -eq $x for null checks.

$Matches is empty or shows an old value after -match

Cause: the left operand was an array (no $Matches), or the match failed and $Matches still holds the previous successful match.

Fix: match one string at a time and use $Matches only inside if ($s -match …) { } (Module 3).

Unexpected token '?' / '&&' in expression or statement

Cause: the script runs in Windows PowerShell 5.1, which has no ternary, null-coalescing or chain operators.

$PSVersionTable.PSVersion

Fix: run it with pwsh and add #Requires -Version 7.0 (or higher) at the top so 5.1 refuses clearly.

Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Cause: the -f template references {1} but only one argument was given — or a literal brace needs escaping.

'{0} {1}' -f 'a', 'b'
'{{literal}} {0}' -f 'x'     # {{ }} for literal braces
Command-line exercises
1. Without a pipeline, get the distinct 4xx status codes from $status (the int array from the lab), sorted.
($status -ge 400) -lt 500 | Sort-Object -Unique
400
401
404

Two chained filters: the first keeps codes ≥ 400, the second keeps those < 500. Comparison operators of equal precedence run left to right, so $status -ge 400 -lt 500 gives the same result (verified), but the parentheses make the intent visible.

2. Print “prod servers: 6 (50.0%)” using -f.
$s = Import-Csv ~/pslab/data/servers.csv
$p = @($s.Env -eq 'prod').Count
'prod servers: {0} ({1:P1})' -f $p, ($p / $s.Count)
Scenario analysis
A teammate wants to block deployments to any environment listed in $frozen = 'prod','staging' and wrote if ($frozen -like "*$target*") { exit 1 }. With $target = 'dev' it works; what can go wrong?

With a collection on the left, -like filters, and the wildcards turn an exact question into a substring question. Verified on 7.6.10: $target = 'ag' matches staging; an empty $target becomes '**' and matches prod,staging (every deployment blocked, or — with -notlike — every one allowed); $target = 'st[' throws “The specified wildcard character pattern is not valid”. The intent is exact membership: if ($target -in $frozen) { exit 1 }, plus [ValidateSet('dev','staging','prod')] on the parameter (Lesson 3).

Verified teaching videos

▶
Learn PowerShell in Less Than 2 Hours — K12 Engineer
English · operators and comparisons in a hands-on tour
▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
English · comparison and logic in scripts

No verified video covers the collection-on-the-left behavior or the PowerShell 7 null operators specifically; use the animation and the documentation below.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: five status codes on a conveyor; “-ge 500” acts as a sieve and only 500 and 503 drop through.
Narration: with a collection on the left, a comparison is a filter.
Shot 2 · 20–45s
Visual: an if statement receives a single 0 and stays red; with two zeros it turns green.
Narration: inside if, the filtered result is judged by truthiness — so say what you mean with -contains or Count.
Shot 3 · 45–70s
Visual: four doors labelled -eq, -like, -match, -contains, each with an example from servers.csv.
Narration: exact value, wildcard, regex or membership — four different questions.
Shot 4 · 70–90s
Visual: ?? fills a missing config value; ${s}?.Length with and without braces.
Narration: PowerShell 7 adds ternary, null-coalescing and chain operators. Remember the braces.
or score ≥ 70% on the Quiz

Module 3 · Strings and regular expressions: $Matches, named groups, -replace, -split / -join

13:00 – 21:00 · PowerShell's string operators are regular-expression operators: one pattern with named groups turns an nginx log line into fields, casts turn the fields into types, and a [pscustomobject] turns them into an object the rest of the pipeline understands
8 mincore animation★★★★★
Learning objectives
  • Use -match on a single string and read $Matches by number and by name ((?<status>\d{3}) → $Matches.status), and know when $Matches is not updated.
  • Write one regex for the nginx combined format and turn a log line into a typed object — the core animation of this lesson.
  • Use -replace with $1, ${name} and a script block, in single quotes; know that -replace and -split take regexes while .Replace() and .Split() do not.
  • Use -split (regex, max count, SimpleMatch, unary form), -join, [regex]::Matches() and Select-String -AllMatches.
  • Control case sensitivity: -cmatch, -creplace, Select-String -CaseSensitive.
Prerequisites: Modules 1–2. Importance:★★★★★ (text from logs, native tools and APIs must become objects before you can trust any number)

What: .NET regular expressions, case-insensitive by default

PowerShell's -match, -replace, -split, switch -Regex and Select-String all use the .NET regex engine. It is close to Perl/PCRE (grep -P), richer than grep -E: \d \s \S \w, lazy quantifiers *?, lookarounds (?=…), and named groups (?<name>…). Like every comparison operator they are case-insensitive by default; the c-prefixed forms are case-sensitive.

TokenMeaningUsed in the log regex for
^ / $Start / end of the stringMake the whole line match, not a fragment
\S+One or more non-space charactersIP, ident, user, path
\[(?<time>[^\]]+)\]Literal brackets around “anything but ]”The timestamp
"(?<method>[A-Z]+) (?<path>\S+) [^"]*"Quoted requestMethod, path; the protocol is skipped
(?<status>\d{3}) (?<bytes>\d+)Exactly three digits, then digitsStatus and size
"(?<ua>.*)"$Greedy “everything” up to the final quoteThe User-Agent — including line 307's it's \x22quoted\x22

Why: one regex beats a split

Splitting on spaces (-split ' ') gives 12 fields for line 1 but 15 for line 307, because the User-Agent contains spaces: $f[8] is still the status (it comes before the User-Agent), but the User-Agent is cut into four pieces and “last field” logic such as $f[-1] returns +https://example.com/bot)". Any format whose quoted fields can contain spaces — and nginx's log_format can put them anywhere — breaks position-based parsing. A regex describes the structure of the line, so quoted parts with spaces are handled by [^"]* and .*. Named groups make the code self-documenting: $Matches.status instead of $fields[8].

How: the rules of $Matches

  1. $string -match $pattern returns True/False and, on success, fills $Matches (a hashtable): key 0 is the whole match, then numbered and named groups.
  2. On failure, $Matches is not cleared — it still holds the previous success. Only read it inside if ($s -match …) { }.
  3. With an array on the left, -match filters (Module 2) and does not set $Matches.
  4. Group values are always strings; cast them ([int]$Matches.status).
  5. For all matches in one string, use [regex]::Matches() or Select-String -AllMatches; -match stops at the first.

When: -replace, -split, -join and friends

OperationRegex?Notes
$s -replace 'pat', 'rep'YesAll occurrences; $1, ${name}, $$ (literal $) in the replacement — use single quotes so PowerShell does not expand $1. A script block replacement ({ $_.Value … }, 6.1+) computes each replacement.
$s.Replace('a', 'b')NoLiteral and case-sensitive
$s -split 'pat', -split $sYes / whitespace-split 'pat', N limits pieces; -split '.', 0, 'SimpleMatch' for literal; unary -split splits on runs of whitespace and drops empty ends (like awk)
$a -join ', ', -join $a—Join with a separator / with nothing
[regex]::Escape($text)—Make user input safe inside a pattern
Common misconceptions① “-replace is literal” — it is a regex: '1.2.3' -replace '.', '-' gives -----. ② “"_$1" works” — in double quotes PowerShell expands $1 (an empty variable) before the regex engine sees it: web_.prod. ③ “A failed -match clears $Matches” — it keeps the old value. ④ “-split ' ' collapses spaces” — it creates empty strings; use '\s+' or unary -split. ⑤ “\d{3} finds the status code” — unanchored, it also finds 203 in the IP and 202 in 2026; include context ('" (\d{3}) '). ⑥ “Select-String is case-sensitive like grep” — it is case-insensitive unless you add -CaseSensitive.

Diagram: one log line, seven named groups

198.51.100.23 - - [24/Nov/2026:10:07:15 +0000] "POST /login HTTP/1.1" 401 64 "-" "python-requests/2.32.5" ip\S+ time\[([^\]]+)\] method[A-Z]+ path\S+ status\d{3} bytes\d+ ua"(.*)"$ $Matches (Hashtable of strings)ip='198.51.100.23' time='24/Nov/2026:10:07:15 +0000' status='401' … casts: [int] status · [long] bytes · ParseExact(time) → UTC DateTime [pscustomobject] ClientIP · Time · Method · Path · Status · Bytes · UserAgent
Figure 3-1: text → groups → typed values → object. Everything downstream (Group-Object, Measure-Object, JSON) works on the object

Diagram: which string tool?

Test-match / -notmatch-like (wildcard)switch -RegexSelect-String (files) Extract$Matches (first match)[regex]::Matches (all)Select-String -AllMatchesnamed groups Change-replace (regex, $1)-creplace (case).Replace() (literal)script block replace Cut and glue-split (regex)-split (unary)-join / -f.Split() (literal)
Figure 3-2: operators use regexes; .NET string methods are literal and case-sensitive

Core animation: from a log line to an object

Choose a line from access.log (or a broken one) and watch the regex engine fill the named groups, the casts produce types, and the object appear. All values are the real 7.6.10 results for that line.

Ready.
Real mechanism behind the animation -match calls Regex.Match() with RegexOptions.IgnoreCase; PowerShell caches compiled patterns, so using the same pattern string in a loop is cheap. On success it builds $Matches from the Groups collection (named groups by name, unnamed ones by number). The casts and the [pscustomobject] are ordinary PowerShell conversions — that is where text stops and objects begin.

Command reference

SyntaxPurposeNotes
$s -match '(?<n>…)'; $Matches.nTest + captureScalar left only; not cleared on failure
$s -replace 'pat', '$1'Regex replaceSingle quotes; ${name}; $$ for a literal $
$s -replace 'pat', { $_.Value }Computed replacement$_ is a Match object
$s -split 'pat', NSplit into at most N pieces'SimpleMatch' option for literal
[regex]::Matches($s, 'pat')All matches with positions.Value, .Index, .Groups
Select-String -Pattern p -Path f -AllMatchesgrep with objectsLineNumber, Line, Matches; -CaseSensitive, -NotMatch, -Context
[regex]::Escape($userInput)Literal text inside a patternPrevents regex injection
$lines = Get-Content ./data/access.log
$re = '^(?<ip>\S+) \S+ \S+ \[(?<time>[^\]]+)\] "(?<method>[A-Z]+) (?<path>\S+) [^"]*" (?<status>\d{3}) (?<bytes>\d+) "[^"]*" "(?<ua>.*)"$'
$lines[0] -match $re
$Matches.ip, $Matches.status, $Matches['path'] -join ' | '
$Matches.status.GetType().Name
'no match here' -match $re
$Matches.ip                    # still the old value!
True
203.0.113.7 | 200 | /healthz
String
False
203.0.113.7

How to verify: after a False, $Matches still answers — proof that you must never read it outside the if. Common mistake: $lines -match $re; $Matches.ip — the array form sets nothing. Production use: keep the pattern in one variable with a comment per group, and count lines that do not match.

From groups to a typed object

$inv = [cultureinfo]::InvariantCulture
foreach ($n in 151, 307) {
  if ($lines[$n - 1] -match $re) {
    [pscustomobject]@{
      Line      = $n
      ClientIP  = $Matches.ip
      Time      = [datetime]::ParseExact($Matches.time, 'dd/MMM/yyyy:HH:mm:ss zzz', $inv).ToUniversalTime()
      Request   = '{0} {1}' -f $Matches.method, $Matches.path
      Status    = [int]$Matches.status
      Bytes     = [long]$Matches.bytes
      UserAgent = $Matches.ua
    }
  }
}
Line      : 151
ClientIP  : 198.51.100.23
Time      : 11/24/2026 10:07:15 AM
Request   : POST /login
Status    : 401
Bytes     : 64
UserAgent : python-requests/2.32.5

Line      : 307
ClientIP  : 192.0.2.66
Time      : 11/24/2026 10:14:57 AM
Request   : GET /
Status    : 200
Bytes     : 4120
UserAgent : O'Reilly-Bot/2.0 (it's \x22quoted\x22; +https://example.com/bot)

-replace

'web-01.prod' -replace '-(\d+)', '_$1'
'web-01.prod' -replace "-(\d+)", "_$1"
'web-01.prod' -replace '(?<n>\d+)', '#${n}'
'24/Nov/2026:10:00:01' -replace '(\d+)/(\w+)/(\d+)', '$3-$2-$1'
'1.2.3' -replace '.', '-'
'1.2.3' -replace '\.', '-'
'1.2.3'.Replace('.', '-')
'GET /API/Orders' -replace 'api', 'v2'
'GET /API/Orders' -creplace 'api', 'v2'
(Get-Content ./data/access.log -TotalCount 1) -replace '^(\d+\.\d+\.\d+)\.\d+', '$1.x'
'client 198.51.100.23 sent 72 requests' -replace '\d+(?= requests)', { [int]$_.Value * 2 }
web_01.prod
web_.prod
web-#01.prod
2026-Nov-24:10:00:01
-----
1-2-3
1-2-3
GET /v2/Orders
GET /API/Orders
203.0.113.x - - [24/Nov/2026:10:00:01 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"
client 198.51.100.23 sent 144 requests

Line 2 is the double-quote trap; line 10 anonymizes the last IP octet (a common GDPR step before sharing logs); the last line uses a lookahead (?= requests) and a script-block replacement.

-split and -join

'web,api' -split ','
('a  b   c' -split ' ').Count
('a  b   c' -split '\s+').Count
(-split '  a  b   c ').Count
('a.b.c' -split '.').Count
'a.b.c' -split '.', 0, 'SimpleMatch'
'k=v=w' -split '=', 2
((Get-Content ./data/access.log -TotalCount 1) -split '"')[1]
'web', 'api', 'db' -join ' | '
-join ('a', 'b')
web
api
6
3
3
6
a
b
c
k
v=w
GET /healthz HTTP/1.1
web | api | db
ab

'a.b.c' -split '.' returns 6 empty strings: every character is a separator.

All matches: [regex]::Matches and Select-String

$line = Get-Content ./data/access.log -TotalCount 1
$m = [regex]::Matches($line, '\d{3}')
$m.Count; $m.Value -join ','
[regex]::Matches($line, '" (\d{3}) ')[0].Groups[1].Value
(Select-String -Path ./data/access.log -Pattern '" 50[023] ').Count
(Select-String -Path ./data/access.log -Pattern '\d{3}' | Select-Object -First 1).Matches.Value -join ','
(Select-String -Path ./data/access.log -Pattern '\d{3}' -AllMatches | Select-Object -First 1).Matches.Value -join ','
(Select-String -Path ./data/access.log -Pattern 'POST /LOGIN').Count
(Select-String -Path ./data/access.log -Pattern 'POST /LOGIN' -CaseSensitive).Count
Select-String -Path ./data/access.log -Pattern '" 401 ' | Select-Object -First 2 LineNumber, Line | Format-Table -Wrap
5
203,113,202,000,200
200
20
203
203,113,202,000,200
23
0

LineNumber Line
---------- ----
       151 198.51.100.23 - - [24/Nov/2026:10:07:15 +0000] "POST /login HTTP/1.1" 401 64 "-" "python-requests/2.32.5"
       152 198.51.100.23 - - [24/Nov/2026:10:07:16 +0000] "POST /login HTTP/1.1" 401 64 "-" "python-requests/2.32.5"

The unanchored \d{3} found five “status codes” in one line: 203 and 113 from the IP, 202 from 2026, 000 from +0000, and finally 200. Context in the pattern fixes it. POST /LOGIN finds 23 lines (6 × 401 + 17 × 302) only because Select-String ignores case.

Goal: Prove that a split breaks the User-Agent of line 307, then parse every line of access.log with the named-group regex and verify the totals from Lesson 1. Environment: pwsh 7.6 in ~/pslab. Cost: none.

Field counts with a naive split:
Set-Location ~/pslab
$lines = Get-Content ./data/access.log
($lines[0] -split ' ').Count; ($lines[306] -split ' ').Count
($lines[306] -split ' ')[-1]
12
15
+https://example.com/bot)"
Parse every line and count failures (paste $re from the Commands tab first):
$ok = 0; $bad = 0
foreach ($l in $lines) { if ($l -match $re) { $ok++ } else { $bad++ } }
"parsed=$ok unparsed=$bad"
parsed=611 unparsed=0
Objects → numbers you can trust:
$rows = foreach ($l in $lines) {
  if ($l -match $re) { [pscustomobject]@{ Method = $Matches.method; Status = [int]$Matches.status; Bytes = [long]$Matches.bytes } }
}
$rows | Group-Object Method -NoElement | Format-Table Name, Count
($rows | Measure-Object Bytes -Sum).Sum
($rows | Where-Object Status -ge 500).Count
Name Count
---- -----
GET    526
POST    85

2918056
20

GET 526 / POST 85, total bytes 2,918,056 and 20 server errors — exactly the dataset facts from Lesson 1's setup page.

Decode nginx's escaped quotes with a literal (non-regex) replace:
$lines[306].Replace('\x22', '"')
192.0.2.66 - - [24/Nov/2026:10:14:57 +0000] "GET / HTTP/1.1" 200 4120 "-" "O'Reilly-Bot/2.0 (it's "quoted"; +https://example.com/bot)"

With -replace you would need the regex '\\x22' (an escaped backslash); the string method avoids the second escaping layer.

Cleanup: nothing was written to disk.

Case 1: the dashboard that counted years as errors

Problem: An alert counted “5xx responses” with Select-String ' 5\d\d ' and fired every few minutes at night. Root cause: the pattern also matched byte counts such as 512 ; on this dataset the loose version finds 37 lines instead of 20 (Lesson 1, Module 6). Fix: anchor the pattern to the structure ('" 5\d\d ') or, better, parse into objects and filter Status -ge 500.

Case 2: stale $Matches assigned the wrong client

Problem: A security report attributed failed logins to the wrong IP for a few lines. Root cause: the loop did $line -match $re | Out-Null; $ip = $Matches.ip; lines that did not match (truncated by log rotation) reused the previous line's $Matches. Fix: only read $Matches inside if ($line -match $re) { … } else { $unparsed++ }, and report the unparsed count.

Case 3: regex injection from a parameter

Problem: Get-LogLines -Path $p -Text $userText built -match $userText; a user searched for C++ (x86) and got “Nested quantifier” errors, another searched .* and dumped everything. Root cause: user text used as a pattern. Fix: -match [regex]::Escape($userText), or Select-String -SimpleMatch.

Common errors and fixes

-replace inserts nothing where $1 should be

Cause: the replacement was in double quotes; PowerShell expanded $1 to an empty string.

'web-01' -replace '-(\d+)', '_$1'     # single quotes
"web-01" -replace "-(\d+)", "_`$1"    # or escape the $
parsing "…" - Unterminated [] set / Quantifier {x,y} following nothing / Nested quantifier

Cause: an invalid regex — often a literal [, (, + or ? that needed escaping.

[regex]::Escape('[draft] notes.md')    # \[draft]\ notes\.md

Fix: escape literal text; test patterns on one line before running them on a file.

$Matches is $null or has unexpected keys

Cause: no successful scalar match yet in this scope, an array on the left, or the match happened inside a different scope (a function's $Matches is local to it).

Fix: test the result of -match, and read $Matches right after it in the same scope.

A regex works in regex101 but not in PowerShell

Cause: a different flavor (PCRE/JavaScript), case sensitivity (PowerShell ignores case by default), or a backtick/$ expanded in double quotes.

Fix: choose the .NET flavor in the tester, use single quotes, and add (?-i) or -cmatch when case matters.

Command-line exercises
1. List the distinct paths that received a 404, using Select-String and a named group.
Select-String -Path ~/pslab/data/access.log -Pattern '"[A-Z]+ (?<path>\S+) [^"]*" 404 ' |
    ForEach-Object { $_.Matches[0].Groups['path'].Value } | Sort-Object -Unique
/api/orders/1042
2. Rewrite every timestamp in line 1 into ISO format 2026-11-24T10:00:01Z with a script-block replacement.
(Get-Content ~/pslab/data/access.log -TotalCount 1) -replace '\[([^\]]+)\]', {
    '[{0:yyyy-MM-ddTHH:mm:ssZ}]' -f [datetime]::ParseExact($_.Groups[1].Value, 'dd/MMM/yyyy:HH:mm:ss zzz', [cultureinfo]::InvariantCulture).ToUniversalTime() }
203.0.113.7 - - [2026-11-24T10:00:01Z] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"
Scenario analysis
Your team parses a vendor's CSV-like log by $line.Split(','). Some fields are quoted and contain commas; the vendor also sometimes adds a field at the end. How do you make the parser robust?

If it is real CSV, do not write a parser: ConvertFrom-Csv -Header … / Import-Csv handle quotes and embedded commas (Module 7, and edge-01's "web,api"). If it is a custom format, describe its structure with one anchored regex with named groups, allow optional trailing fields ((?:,(?<extra>.*))?$), count unparsed lines and fail the job when the count exceeds a threshold, and keep sample lines (like line 307) as test cases (Lesson 8).

Verified teaching videos

▶
POWERSHELL TUTORIAL REGEX, MATCH AND REPLACE [Highway to PowerShell - Episode 8] — Simon Automates
English · -match, -replace and Select-String
▶
Regex in PowerShell: How to grasp it and why you should grasp it — SQLBits
English · conference talk, deeper regex usage
▶
PowerShell Regex Tutorial: Pattern Matching with -match Operator for Beginners — CodeLucky
English · short beginner introduction to -match

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: line 307 split on spaces; the User-Agent shatters into four fields and the “last field” arrow points at a fragment.
Narration: splitting on spaces breaks as soon as a field contains a space.
Shot 2 · 20–50s
Visual: coloured brackets for seven named groups snap onto the line; $Matches appears as a table.
Narration: one regex with named groups describes the whole line.
Shot 3 · 50–75s
Visual: “401” passes through [int], the timestamp through ParseExact; a PSCustomObject card assembles.
Narration: cast the groups, build an object, and the text problem is gone.
Shot 4 · 75–90s
Visual: a failed match with an old $Matches value flashing red.
Narration: read $Matches only inside the if.
or score ≥ 70% on the Quiz

Module 4 · Collections: arrays, List[T], hashtables, [ordered], member enumeration

21:00 – 28:00 · Arrays are fixed-size and += copies them; lists grow in place; hashtables are unordered key lookups and the fastest counters you have; member enumeration reads a property from every element — except when the collection has that property itself
7 min@() · List[T] · @{} · [ordered]★★★★☆
Learning objectives
  • Create arrays with , and @(), and use @( … ) to guarantee an array even when a command returns one object or none.
  • Measure why += on an array is quadratic, and use [System.Collections.Generic.List[T]] or assign a loop's output instead.
  • Use hashtables for configuration, lookups (by IP) and counters (by status); know their keys are case-insensitive and their order is not guaranteed; use [ordered] when order matters.
  • Use member enumeration ($servers.Name) and know when it does not apply (.Count, .Length).
  • Build [pscustomobject] from a hashtable and pass parameters by splatting (@params).
Prerequisites: Modules 1–3. Importance:★★★★☆

What: the four collections you will use daily

CollectionCreateGrows?Use for
Array Object[]1, 2, 3, @(), @(cmd), loop outputNo — += creates a new array and copiesCommand output, small fixed lists
List List[T][System.Collections.Generic.List[object]]::new()Yes — .Add(), .Remove()Collecting results in loops, especially with conditions
Hashtable@{ Key = 'Value' }Yes — $h[k] = vConfig, lookups, counters, splatting
Ordered dictionary[ordered]@{ … }YesAnything shown to humans or serialized (JSON keys, CSV columns)

Why: arrays are fixed-size

.NET arrays cannot grow. $arr += $x allocates a new array of length n+1 and copies the old elements, so a loop of n appends copies about n²/2 elements. Measured on 7.6.10: 10,000 appends took ~95 ms, 40,000 took ~5,200 ms — four times the data, about 55 times the time. A List[int] took ~170 / ~570 ms (linear), and simply assigning the loop's output ($out = foreach (…) { $i }) took ~10–25 ms. Another side effect: += creates a new array, so other variables that pointed to the old one do not see the change.

How: hashtables

  • Access: $h.Key, $h['Key'], nested $cfg.Environments.prod.HealthUrl. Missing keys return $null — but under Set-StrictMode -Version Latest the dot form $h.Missing throws “The property 'Missing' cannot be found”, while the index form $h['Missing'] still returns $null (verified on 7.6.10). Use the index form or .ContainsKey() for optional keys in strict scripts.
  • Keys are case-insensitive ($h['PROD'] finds prod); .ContainsKey() tests existence even when the value is $null.
  • Order: a plain hashtable has no defined order, and in PowerShell 7 it changes between processes because .NET randomizes string hash codes. Lesson 1's run returned Environments as staging, prod, dev; five fresh pwsh processes on the same machine returned five orders including prod, dev, staging and dev, staging, prod. Sort keys or use [ordered].
  • Counter: $count[$key]++ works on a missing key ($null + 1 = 1). Lookup: build once ($byIp[$s.IP] = $s), then each lookup is O(1) instead of a Where-Object scan.
  • You cannot change a hashtable while enumerating it: iterate over a copy, @($h.Keys).

When: member enumeration, [pscustomobject] and splatting

Member enumeration: $servers.Name returns the Name of every element. It does not apply when the collection itself has the member: (Get-ChildItem -File).Length is the array's length (4), not the file sizes — use .ForEach('Length') or Select-Object -ExpandProperty Length. [pscustomobject]@{…} creates an object whose properties keep the hashtable literal's order. Splatting passes a hashtable as named parameters: Get-Content @params (note @, not $) — Lesson 3 uses it everywhere.

Common misconceptions① “+= appends” — it copies; fine for 10 items, wrong for 10,000. ② “A hashtable remembers insertion order” — it does not, and the order can differ on the next run; use [ordered]. ③ “(Get-ChildItem).Length gives file sizes” — it gives the element count. ④ “A command that returns one object returns an array” — it returns the object itself; wrap with @() before using .Count or indexes (a single string's [0] is its first character). ⑤ “[pscustomobject]$hashtable keeps the order” — only a literal right after the cast keeps it; casting a variable uses the hashtable's (random) order. ⑥ “Hashtable keys are case-sensitive like Python dicts” — not by default.

Diagram: += vs List.Add

$arr += 4 (Object[]) 1 2 3 copy all 1 2 3 4 new array every time → n appends copy ~n²/2 elements 10k: ~95 ms · 40k: ~5,200 ms (measured) $list.Add(4) (List[int]) 1 2 3 4 · · spare capacity; doubles when full → linear 10k: ~170 ms · 40k: ~570 ms (measured) Best in PowerShell: let the loop produce output and assign it$out = foreach ($i in 1..$n) { $i } → the engine collects into a list internally (~10–25 ms here)Use List[T] when you add conditionally from several places, or need .Remove() / .Insert()
Figure 4-1: appending to an array copies it; a list grows in place

Diagram: a hashtable as counter and lookup

611 log lines... " 200 ...... " 401 ...... " 200 ...... " 503 ...$count[$Matches.s]++ $count (key → value)'200' → 463'401' → 6'503' → 8 …11 keysone pass, O(1) per lineorder not guaranteed → sort $byIp lookup'10.20.1.31' → web-01 (staging)'10.30.2.51' → edge-01 (prod)build once from servers.csvthen $byIp[$req.ClientIP]instead of Where-Object per line
Figure 4-2: hashtables replace nested loops with one pass plus constant-time lookups

What happens in memory

Step through common collection operations and see what is created, copied or shared. Results reproduced on 7.6.10.

Ready.

Command reference

SyntaxPurposeNotes
@(cmd)Always an array0, 1 or n results → .Count works
,$xWrap in a one-element arrayStops the pipeline from unrolling it
[System.Collections.Generic.List[object]]::new()Growable list.Add(), .Remove(), .Contains(), .ToArray()
@{}, [ordered]@{}Hashtable / ordered dictionary.Keys, .Values, .ContainsKey(), .Remove(), .GetEnumerator()
Group-Object X -AsHashTableGroup into a lookupValues are lists of objects
$coll.Prop / .ForEach('Prop')Member enumerationUse .ForEach() when the collection has the member itself
[pscustomobject]@{…}Object from a literalProperty order = literal order
cmd @paramsSplattingHashtable → named, array → positional
$one = Get-ChildItem ./data -Filter servers.csv;    $one.GetType().Name
$arr = @(Get-ChildItem ./data -Filter servers.csv); $arr.GetType().Name, $arr.Count -join ' '
$b = 1, 2, 3; $b.IsFixedSize
try { $b.Add(4) } catch { $_.Exception.Message }
$c = $b; $b += 4; "b=$($b -join ',')  c=$($c -join ',')"
$list = [System.Collections.Generic.List[string]]::new()
$list.Add('web-01'); $list.Add('db-01'); $list.Remove('db-01') | Out-Null; $list.Count
FileInfo
Object[] 1
True
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
b=1,2,3,4  c=1,2,3
1

Measure the cost of +=

foreach ($n in 10000, 40000) {
  [pscustomobject]@{
    N          = $n
    'Array +=' = [int](Measure-Command { $arr = @(); foreach ($i in 1..$n) { $arr += $i } }).TotalMilliseconds
    'List.Add' = [int](Measure-Command { $list = [System.Collections.Generic.List[int]]::new(); foreach ($i in 1..$n) { $list.Add($i) } }).TotalMilliseconds
    'Assign loop output' = [int](Measure-Command { $out = foreach ($i in 1..$n) { $i } }).TotalMilliseconds
  }
}
    N Array += List.Add Assign loop output
    - -------- -------- ------------------
10000       93      169                 23
40000     5220      602                 10

    N Array += List.Add Assign loop output
    - -------- -------- ------------------
10000       99      171                  8
40000     5249      535                  8

How to verify: look at the ratio, not the absolute numbers: ×4 data gave ×55 time for += and ×3.5 for List.Add. Note that for 10,000 items += is even faster than calling a .NET method in a loop — the problem is growth. Production use: assign the loop's output; use List[T] when you add from several branches.

Hashtables

$h = @{ dev = 1; staging = 2; prod = 3 }; $h.Keys -join ', '
$o = [ordered]@{ dev = 1; staging = 2; prod = 3 }; $o.Keys -join ', '
$o[0]; $o['prod']; $h['PROD']
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
$cfg.Environments.prod.HealthUrl
$cfg.Health.BackoffSec -join ','
$null -eq $cfg.Missing
$cfg.ContainsKey('Backup')
staging, dev, prod
dev, staging, prod
1
3
3
https://shop.example.com/healthz
1,2,4
True
True
# five fresh processes, same machine, same command
1..5 | ForEach-Object { pwsh -NoProfile -Command { (Import-PowerShellDataFile ./data/opskit.config.psd1).Environments.Keys -join ', ' } }
prod, staging, dev
dev, staging, prod
prod, staging, dev
prod, staging, dev
staging, prod, dev

Passing a script block to pwsh -Command from inside PowerShell avoids a quoting layer (Lesson 1, Module 7): the block is sent to the child as encoded text.

Counter and lookup

$byStatus = @{}
foreach ($line in Get-Content ./data/access.log) {
    if ($line -match '" (?<s>\d{3}) ') { $byStatus[$Matches.s]++ }
}
$byStatus.GetEnumerator() | Sort-Object Name | Format-Table -AutoSize
$byIp = @{}
foreach ($s in Import-Csv ./data/servers.csv) { $byIp[$s.IP] = $s }
$byIp['10.20.1.31'] | Format-Table Name, Env, Role
Name Value
---- -----
200  463
201  54
301  12
302  17
304  18
400  3
401  6
404  18
500  8
502  4
503  8

Name   Env     Role
----   ---     ----
web-01 staging web

The client 10.20.1.31 that produced the four 502s (lines 458–461) is the staging web-01 — a join of log data and inventory in one lookup.

Member enumeration, objects, splatting

$servers = Import-Csv ./data/servers.csv
$servers.Name -join ','
($servers.Name | Sort-Object -Unique) -join ','
(Get-ChildItem ./data -File).Length
(Get-ChildItem ./data -File).ForEach('Length') -join ','
$p = [pscustomobject]@{ Name = 'web-01'; Env = 'prod'; Port = 8080 }
$p.PSObject.Properties.Name -join ','
$params = @{ Path = './data/access.log'; TotalCount = 1 }
Get-Content @params
$h = @{ a = 1; b = 2 }
try { foreach ($k in $h.Keys) { $h[$k] = 0 } } catch { 'Error: ' + $_.Exception.Message }
foreach ($k in @($h.Keys)) { $h[$k] = 0 }; ($h.Values | Measure-Object -Sum).Sum
web-01,api-01,db-01,web-01,api-01,db-01,web-01,web-02,api-01,edge-01,db-01,bastion-01
api-01,bastion-01,db-01,edge-01,web-01,web-02
4
80646,1599,777,600
Name,Env,Port
203.0.113.7 - - [24/Nov/2026:10:00:01 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"
Error: Collection was modified; enumeration operation may not execute.
0

Goal: Build a requests-per-client counter, join it with the inventory, and compare it with Group-Object. Environment: pwsh 7.6 in ~/pslab. Cost: none.

Count requests per client with a hashtable:
Set-Location ~/pslab
$perClient = @{}
foreach ($line in Get-Content ./data/access.log) { $perClient[($line -split ' ', 2)[0]]++ }
$perClient.Count
$perClient.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 3 Name, Value
11

Name          Value
----          -----
198.51.100.23    72
203.0.113.7      66
192.0.2.11       65
Same answer with Group-Object (slower on large data, but one line):
Get-Content ./data/access.log | Group-Object { ($_ -split ' ', 2)[0] } -NoElement |
    Sort-Object Count -Descending | Select-Object -First 3 Name, Count
Name          Count
----          -----
198.51.100.23    72
203.0.113.7      66
192.0.2.11       65
Join with the inventory: which clients are our own servers?
$byIp = @{}; foreach ($s in Import-Csv ./data/servers.csv) { $byIp[$s.IP] = $s }
$report = foreach ($ip in $perClient.Keys | Sort-Object) {
    if ($byIp.ContainsKey($ip)) {
        [pscustomobject]@{ ClientIP = $ip; Server = $byIp[$ip].Name; Env = $byIp[$ip].Env; Requests = $perClient[$ip] }
    }
}
$report | Format-Table
ClientIP   Server Env     Requests
--------   ------ ---     --------
10.10.1.21 web-01 dev           62
10.10.1.22 api-01 dev           60
10.20.1.31 web-01 staging       60
Cleanup: nothing was written to disk.

Case 1: an inventory export that took 40 minutes

Problem: A nightly script built a 60,000-row report with $rows += [pscustomobject]@{…}. It ran in minutes in test (2,000 rows) and 40 minutes in production. Root cause: quadratic copying. Fix: $rows = foreach (…) { [pscustomobject]@{…} }; the run dropped to seconds. Lesson: test with production-sized data.

Case 2: a config diff that was always “changed”

Problem: A drift check serialized a hashtable to JSON and compared it with yesterday's file; it reported drift every run. Root cause: hashtable key order differs between processes in PowerShell 7, so the JSON text differed. Fix: use [ordered] or sort keys before serializing, and compare objects (Compare-Object on properties) instead of text.

Case 3: “.Count is empty” on one server

Problem: $vms = Get-Something; if ($vms.Count -gt 5) … behaved strangely on a subscription with exactly one VM, and in Windows PowerShell 2.0-era scripts .Count was $null. Root cause: one result is not an array. Modern PowerShell adds an intrinsic .Count to scalars, but indexing still bites (a single string's [0] is a character). Fix: $vms = @(Get-Something).

Common errors and fixes

Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."

Cause: .Add() on an array.

Fix: use [System.Collections.Generic.List[object]], or += for a handful of items.

Collection was modified; enumeration operation may not execute.

Cause: changing a hashtable or list inside a foreach over the same collection.

foreach ($k in @($h.Keys)) { $h[$k] = 0 }
Item has already been added. Key in dictionary: 'web-01'

Cause: duplicate keys in a hashtable literal or .Add() — Name is not unique in servers.csv.

Fix: use a unique key ("$($s.Env)/$($s.Name)") or assignment $h[$k] = $v (last one wins).

JSON/CSV columns appear in a different order every run

Cause: a plain hashtable was the source.

Fix: [ordered]@{…} or [pscustomobject]@{…} literals; Select-Object with an explicit property list before exporting.

Command-line exercises
1. Build an ordered dictionary of environment → number of servers from servers.csv, in the order dev, staging, prod.
$s = Import-Csv ~/pslab/data/servers.csv
$o = [ordered]@{}
foreach ($e in 'dev', 'staging', 'prod') { $o[$e] = @($s.Env -eq $e).Count }
$o
Name                           Value
----                           -----
dev                            3
staging                        3
prod                           6
2. Group the servers by environment into a hashtable and print the names of the prod servers.
$g = Import-Csv ~/pslab/data/servers.csv | Group-Object Env -AsHashTable
$g.prod.Name -join ','
web-01,web-02,api-01,edge-01,db-01,bastion-01
Scenario analysis
A script correlates 2 million firewall log lines with 5,000 known hosts using $hosts | Where-Object IP -eq $line.Src inside the loop. It runs for hours. What do you change, and how do you prove it helped?

That is 2,000,000 × 5,000 comparisons through the pipeline. Build a hashtable once ($byIp = @{}; foreach ($h in $hosts) { $byIp[$h.IP] = $h }) and look up $byIp[$src] per line — 2 million constant-time lookups. Collect results by assigning the loop output, not +=. Prove it with Measure-Command on a 10,000-line sample before and after, and check that both versions produce identical output (Compare-Object). Duplicated IPs need a decision: keep the first, the last, or a list per key.

Verified teaching videos

▶
Arrays & Hashtables | 08 | PowerShell Tutorials with PDQ.com — PDQ
English · creating and using arrays and hashtables
▶
PowerShell Where-Object vs Hash Indexing — Matt Hamende
English · hashtable lookups instead of Where-Object scans

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: boxes copied one by one into a longer row every time += runs; a timer explodes at 40,000.
Narration: arrays cannot grow. Plus-equals copies the whole array every time.
Shot 2 · 25–50s
Visual: a list with spare slots; the loop-output version collects silently.
Narration: assign the loop's output, or use a generic List.
Shot 3 · 50–75s
Visual: status codes dropping into labelled buckets; an IP key opens the matching server card.
Narration: hashtables are counters and lookups. One pass, constant-time access.
Shot 4 · 75–90s
Visual: the same three keys shuffle into different orders in three windows; [ordered] lines them up.
Narration: hashtable order is not guaranteed — use ordered when people or files will see it.
or score ≥ 70% on the Quiz

Module 5 · Conditionals: if / elseif / else and switch (-Regex, -Wildcard, -File)

28:00 – 35:00 · if is an expression whose value you can assign; switch is a loop over its input that runs every matching clause unless you break or continue, and it can read a whole file line by line
7 minif · switch · truthiness★★★★☆
Learning objectives
  • Write if / elseif / else chains, and assign the value of an if or switch to a variable.
  • Use switch with values, script-block conditions, arrays (one pass per element), -Wildcard, -Regex (with $Matches), -CaseSensitive and -File.
  • Explain why several clauses can run, and use break (stop the switch) and continue (next input element) on purpose; know that default runs only when nothing else matched.
  • Apply the truthiness rules (0, '', $null, empty arrays are false; 'false' and '0' are true) and avoid = vs -eq and string-vs-number traps.
Prerequisites: Modules 1–3. Importance:★★★★☆

What: if is an expression

if (cond) { … } elseif (cond) { … } else { … } works like in any C-style language. In PowerShell every statement can produce output, so $size = if ($n -gt 600) { 'big' } else { 'small' } assigns the output of the chosen block. For one-line choices the ternary ?: (Module 2) is shorter. Comparisons are operators (-eq, -gt), not symbols: = inside if ( ) is an assignment, and the condition is then the assigned value.

Why: switch is more than a case statement

FeatureBehavior (verified on 7.6.10)
Multiple matchesAll matching clauses run, in order: switch (404) { 404 {…} { $_ -ge 400 } {…} } runs both
breakStops the whole switch (all remaining input)
continueStops this element and moves to the next input element
Array inputThe switch loops: $_ is the current element
defaultRuns only if no other clause matched this element — even if it is written first
Script-block condition{ $_ -ge 500 } — any expression
-Wildcard / -RegexString conditions become patterns; -Regex fills $Matches
-File pathReads the file line by line (streaming) — an efficient line processor
CaseInsensitive unless -CaseSensitive
TypesValues are compared like -eq: switch ('10') { 10 {…} } matches
Empty inputswitch (@()) { default {…} } runs nothing, not even default

How: truthiness

FalseTrue
$false, $null, 0 (any numeric zero), '', empty array @(), an array whose single element is false (@(0), @($null))Everything else, including 'false', '0', ' ', any object, an array with two or more elements (@(0,0))

When: if, switch or a hashtable?

  • if/elseif for a few ordered ranges (-ge 500, -ge 400 …).
  • switch for many patterns, classification of strings, or streaming a file with -File.
  • A hashtable when the mapping is pure data: $tier = @{ web = 'frontend'; db = 'data' }[$role] — easy to move into a config file later.

Bash comparison: case $x in web-*) … ;; esac stops at the first match (like switch -Wildcard with break in every clause). PowerShell's default is to continue matching.

Common misconceptions① “switch stops at the first match” — every matching clause runs unless you break/continue. ② “break in a switch clause skips to the next element” — that is continue; break ends the whole switch. ③ “default written first runs for every element” — it runs only when nothing else matched. ④ “if ($a = 5) compares” — it assigns. ⑤ “if ('false') is false” — non-empty strings are true. ⑥ “$st -gt 1000 compares numbers” — not if $st is the string '200' from a split or CSV.

Flowchart: how switch processes each input element

next input element$_ = element (or file line) clause 1 matches?value / wildcard / regex / { } clause 2 …all clauses are tested defaultonly if none matched yes → run body body ranthen: nothing / continue / break (nothing)test the next clause→ several bodies may run continueskip the remaining clauses→ next input element breakleave the whole switch→ remaining input is ignored
Figure 5-1: switch is a loop over its input; break and continue refer to that loop

switch evaluator

Choose a switch statement and step through which clauses run for which input. Results reproduced on 7.6.10.

Ready.

Command reference

SyntaxPurposeNotes
$v = if (c) { a } else { b }if as an expressionOr c ? a : b
switch ($x) { v {…} { cond } {…} default {…} }Multi-way branchAll matching clauses run
switch -Wildcard / -Regex / -ExactPattern type-Regex sets $Matches
switch -File pathProcess a file line by lineStreams; combine with -Regex
switch -CaseSensitiveCase-sensitive matchingDefault is insensitive
break / continue in a clauseEnd switch / next elementInside a loop, a switch absorbs them
function Get-StatusClass([int]$Status) {
    if     ($Status -ge 500) { 'server-error' }
    elseif ($Status -ge 400) { 'client-error' }
    elseif ($Status -ge 300) { 'redirect' }
    else                     { 'success' }
}
200, 302, 404, 503 | ForEach-Object { "$_ $(Get-StatusClass $_)" }
$size = if ((Get-Content ./data/access.log).Count -gt 600) { 'big' } else { 'small' }; $size
200 success
302 redirect
404 client-error
503 server-error
big
switch (404) { 404 { 'exact 404' } { $_ -ge 400 } { 'script block: >= 400' } default { 'default' } }
'---'
switch (404) { 404 { 'exact 404'; break } { $_ -ge 400 } { 'never reached' } }
'---'
switch (200, 404, 503) {
    { $_ -ge 500 } { "$_ 5xx"; continue }
    { $_ -ge 400 } { "$_ 4xx"; continue }
    default        { "$_ ok" }
}
'---'
switch -Wildcard ('web-01', 'db-01', 'edge-01') {
    'web-*' { "$_ -> web tier" }
    'db-*'  { "$_ -> data tier" }
    default { "$_ -> other" }
}
'---'
switch -Regex ('GET /api/orders', 'POST /login', 'GET /static/app.js') {
    '^(GET|POST) /api/' { "$_ -> API ($($Matches[1]))" }
    '/login$'           { "$_ -> auth" }
    '\.(js|css)$'       { "$_ -> static ($($Matches[1]))" }
}
exact 404
script block: >= 400
---
exact 404
---
200 ok
404 4xx
503 5xx
---
web-01 -> web tier
db-01 -> data tier
edge-01 -> other
---
GET /api/orders -> API (GET)
POST /login -> auth
GET /static/app.js -> static (js)

How to verify: the first statement printed two lines for one input — both clauses matched. Common mistake: forgetting continue in range checks, so a 503 is reported as both 5xx and 4xx. Production use: end every clause with continue when the clauses are meant to be exclusive.

switch -File and the edge cases

$counts = [ordered]@{ api = 0; health = 0; other = 0 }
switch -Regex -File ./data/access.log {
    '"\S+ /api/'     { $counts.api++;    continue }
    '"\S+ /healthz ' { $counts.health++; continue }
    default          { $counts.other++ }
}
$counts.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }
switch ('PROD') { 'prod' { 'matched case-insensitively' } }
switch -CaseSensitive ('PROD') { 'prod' { 'matched' } default { 'no match with -CaseSensitive' } }
switch ('10') { 10 { 'string 10 matched number 10' } }
switch (@()) { default { 'default for an empty collection?' } }
'after the empty switch'
api=280
health=124
other=207
matched case-insensitively
no match with -CaseSensitive
string 10 matched number 10
after the empty switch

api = 216 (/api/orders) + 64 (/api/orders/1042); health = 124; 280 + 124 + 207 = 611.

Comparison and truthiness pitfalls

$st = '200'
if ($st -gt 1000) { "'200' -gt 1000 is TRUE (string comparison)" }
if (1000 -lt $st) { 'numeric' } else { 'number on the left: 1000 -lt 200 is false' }
if ($st = 500) { "assignment, not comparison: `$st is now $st" }
if ('false') { "'false' is truthy" }
if ('0') { "'0' (string) is truthy" }
if (0) { } else { '0 (number) is falsy' }
if (@()) { } else { 'empty array is falsy' }
if (@($null)) { } else { '@($null) is falsy' }
if (@(0, 0)) { 'two zeros are truthy' }
'200' -gt 1000 is TRUE (string comparison)
number on the left: 1000 -lt 200 is false
assignment, not comparison: $st is now 500
'false' is truthy
'0' (string) is truthy
0 (number) is falsy
empty array is falsy
@($null) is falsy
two zeros are truthy

Goal: Classify every line of access.log with one streaming switch -Regex -File, find the first server error, and flag risky servers with script-block conditions. Environment: pwsh 7.6 in ~/pslab. Cost: none.

Status classes in one pass:
Set-Location ~/pslab
$class = [ordered]@{ '2xx' = 0; '3xx' = 0; '4xx' = 0; '5xx' = 0; unparsed = 0 }
switch -Regex -File ./data/access.log {
    '" 2\d\d ' { $class['2xx']++; continue }
    '" 3\d\d ' { $class['3xx']++; continue }
    '" 4\d\d ' { $class['4xx']++; continue }
    '" 5\d\d ' { $class['5xx']++; continue }
    default    { $class.unparsed++ }
}
[pscustomobject]$class | Format-Table
2xx 3xx 4xx 5xx unparsed
--- --- --- --- --------
517  47  27  20        0

517 + 47 + 27 + 20 = 611. [pscustomobject] in front of an ordered dictionary keeps the column order.

Find the first 5xx line — the wrong way first: a line counter in default.
$n = 0
switch -Regex -File ./data/access.log {
    default    { $n++ }
    '" 5\d\d ' { "first 5xx at line ${n}: $($_.Substring(0, 60))"; break }
}
first 5xx at line 54: 192.0.2.10 - - [24/Nov/2026:10:02:48 +0000] "GET /api/orders

Wrong by one: for the 5xx line itself another clause matched, so default did not run and the counter was not incremented. (${n} is needed because $n: would be read as a drive-qualified variable.)

Fix: a clause that always matches:
$n = 0
switch -Regex -File ./data/access.log {
    { $true }  { $n++ }
    '" 5\d\d ' { "first 5xx at line ${n}"; break }
}
(Select-String -Path ./data/access.log -Pattern '" 5\d\d ' | Select-Object -First 1).LineNumber
first 5xx at line 55
55
Script-block conditions on objects: flag servers that need attention.
foreach ($s in Import-Csv ./data/servers.csv) {
    $action = switch ($s) {
        { $_.Env -eq 'prod' -and $_.Monitored -eq 'false' } { 'ALERT: unmonitored prod'; break }
        { $_.Role -like '*,*' }                            { 'review: multi-role'; break }
        default                                            { $null }
    }
    if ($action) { '{0,-11} {1,-8} {2}' -f $s.Name, $s.Env, $action }
}
edge-01     prod     review: multi-role
db-01       prod     ALERT: unmonitored prod
bastion-01  prod     ALERT: unmonitored prod

switch ($s) with a single object runs once with $_ = $s. Note -eq 'false': the CSV value is a string (Module 7 fixes this with JSON).

Cleanup: nothing was written to disk.

Case 1: every 503 was paged twice

Problem: An alert router used switch ($status) { { $_ -ge 500 } { Send-Page 'sev2' } { $_ -ge 400 } { Send-Ticket } }. On-call engineers received a page and a ticket for every 5xx. Root cause: switch runs all matching clauses. Fix: add break (single value) or continue (arrays/files) to each clause, and unit-test the router with 200, 404 and 503.

Case 2: a disk check that never alerted

Problem: $free = (df -h / | Select-Object -Last 1) -split '\s+' | Select-Object -Index 3 followed by if ($free -lt 10) { alert } never fired on Linux. Root cause: $free was the string '7.5G'; '7.5G' -lt 10 is a string comparison ('7' > '1') and is false. Fix: use Get-PSDrive / [IO.DriveInfo] objects (Lesson 4), or parse and cast: [double]($free -replace 'G$').

Case 3: an if that changed the configuration

Problem: if ($cfg.DefaultEnv = 'prod') { … } in a deployment helper made every later step target prod. Root cause: assignment instead of -eq; the assigned non-empty string is truthy. Fix: -eq; PSScriptAnalyzer's PSPossibleIncorrectUsageOfAssignmentOperator rule catches it (Lesson 8).

Common errors and fixes

switch runs more clauses than expected

Cause: several conditions matched; no break/continue.

Fix: end exclusive clauses with continue (or break for a single value); order clauses from most to least specific.

switch -File: No files matching '…' were found.

Cause: a relative path resolved against the current location, or wildcard characters in the name: switch -File treats its path as a wildcard pattern and has no -LiteralPath (7.6.10 rejects it with “The parameter LiteralPath is not valid for the switch statement”).

switch -File (Join-Path $PSScriptRoot 'data/access.log') { … }
switch -File ([WildcardPattern]::Escape('./tmp/[x]/f.txt')) { … }   # verified: reads the file

Fix: build paths from $PSScriptRoot; escape names that contain [ ], or use Get-Content -LiteralPath … | ForEach-Object.

$Matches inside a switch -Regex clause is from the wrong pattern

Cause: several regex clauses matched; $Matches belongs to the clause currently running, and a later clause overwrites it.

Fix: copy what you need inside each clause, and use continue to stop after the first match.

An if branch runs although the value looks false

Cause: the value is a non-empty string such as 'false', '0' or 'False '.

$v.GetType().Name; "[$v]"

Fix: convert at the edge ([bool]::Parse($v), [int]$v) or read typed data (JSON).

Command-line exercises
1. With one switch -Wildcard over (Import-Csv servers.csv).Name, count web, api, db and other servers.
$c = [ordered]@{ web = 0; api = 0; db = 0; other = 0 }
switch -Wildcard ((Import-Csv ~/pslab/data/servers.csv).Name) {
    'web-*' { $c.web++; continue }
    'api-*' { $c.api++; continue }
    'db-*'  { $c.db++;  continue }
    default { $c.other++ }
}
[pscustomobject]$c
web api db other
--- --- -- -----
  4   3  3     2
2. Map a role to a tier with a hashtable instead of a switch, with a fallback.
$tier = @{ web = 'frontend'; api = 'backend'; db = 'data' }
foreach ($r in 'web', 'db', 'bastion') { '{0} -> {1}' -f $r, ($tier[$r] ?? 'unknown') }
web -> frontend
db -> data
bastion -> unknown
Scenario analysis
A log-shipping script uses switch -Regex -File $log { 'ERROR' { Send-Event $_ } 'TIMEOUT' { Send-Event $_ } }. Operators report duplicate events and, occasionally, missing ones. Explain both.

Duplicates: a line such as ERROR: TIMEOUT calling /api matches both clauses, so both run — add continue. Missing ones: matching is case-insensitive, so that is not the cause; check instead whether the file is rotated while being read (-File opens it once), whether the patterns rely on $Matches from the wrong clause, and whether an exception in Send-Event stops the switch (Lesson 5 adds try/catch per line). Keep a counter of processed lines and compare it with the file's line count.

Verified teaching videos

▶
MICROSOFT PowerShell Switch Statement – Regex & File Processing — HardReset_Pro
English · switch with -Regex and file input
▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
English · flow control in scripts

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: the value 404 falls through a column of clauses; two of them light up.
Narration: switch runs every matching clause.
Shot 2 · 20–45s
Visual: “continue” sends the ball to the next input; “break” closes the whole machine.
Narration: continue means next element; break means stop the switch.
Shot 3 · 45–70s
Visual: access.log streams through switch -Regex -File into four counters 517 / 47 / 27 / 20.
Narration: switch can read a file line by line — a fast classifier.
Shot 4 · 70–90s
Visual: the string '200' beats 1000 in a string comparison; a cast fixes it.
Narration: compare numbers as numbers. Put them on the left or cast.
or score ≥ 70% on the Quiz

Module 6 · Loops: foreach vs ForEach-Object, for, while, do, break / continue pitfalls

35:00 – 42:00 · The foreach statement and the ForEach-Object cmdlet look alike but are different things; inside a ForEach-Object script block, break and continue do not act on the pipeline — they jump to the nearest enclosing loop, even across function and script boundaries, or end the script
7 minforeach · ForEach-Object · labels · .Where()★★★★★
Learning objectives
  • Choose between the foreach statement (collection in memory, fastest, cannot be piped directly) and the ForEach-Object cmdlet (streams pipeline input), and recognise the foreach alias after a |.
  • Write for, while, do { } while and do { } until loops, and know that do runs at least once.
  • Reproduce the trap: break/continue inside ForEach-Object leave the enclosing loop or end the script, and return acts like continue.
  • Stop early correctly with Select-Object -First, a foreach statement, or .Where({…}, 'First'); break out of nested loops with labels.
  • Use the .ForEach() and .Where() methods and know their trade-offs.
Prerequisites: Modules 1–5. Importance:★★★★★

What: two things called foreach

foreach ($x in $coll) { } statement… | ForEach-Object { $_ } cmdlet
InputA collection evaluated first, fully, in memoryPipeline objects, one at a time (streaming)
Current itemYour variable ($x)$_ / $PSItem
Speed (100,000 additions, 7.6.10)~110–140 ms~690–720 ms (.ForEach(): ~270–310 ms)
Pipe the outputNot directly — foreach (…) { } | Sort-Object is a parse error; assign it or wrap in $( )Yes
break / continueAct on this loopAct on the nearest enclosing loop outside the pipeline — or stop the script
Extras—-Begin/-End, -Parallel (Lesson 6)

After a |, the word foreach is the alias of ForEach-Object; at the start of a statement it is the keyword. Same word, two meanings — another reason to write full names in scripts.

Why: break and continue inside a script block

The script block you pass to ForEach-Object is not a loop body; it is a block called once per object. break and continue look for the nearest enclosing loop or switch by unwinding the call stack — through the cmdlet, through functions, even through a script called with & or ./. Verified on 7.6.10:

  • Inside a foreach loop: break in ForEach-Object ends the outer foreach loop; continue skips to its next iteration.
  • In a function called from a loop: the caller's loop is broken (“round 1 … after rounds”).
  • With no loop anywhere: the script stops — the remaining statements do not run, and pwsh -File still exits with 0. A script that “succeeds” without doing its last steps.
  • return inside the script block ends only the current invocation — it behaves like continue for the pipeline.

How: the other loops

LoopRunsTypical use
for ($i = 0; $i -lt $n; $i++) { }While the condition is trueIndex-based work (line numbers, every n-th item)
while (cond) { }0 or more timesSearch until found, poll until ready (with a timeout!)
do { } while (cond)At least once, while trueRetry loops
do { } until (cond)At least once, until trueRetry until success
:label foreach (…) { … break label }—Leave nested loops at once
$c.ForEach({ }), $c.Where({ }, 'First', 2)Method on any collectionFast in-memory filtering; modes First, Last, SkipUntil, Until, Split

When: stopping early

To stop a pipeline early, use Select-Object -First N: it stops upstream commands properly. To stop a loop, use a foreach statement with break. Never use break inside ForEach-Object or Where-Object to mean “stop the pipeline”.

Common misconceptions① “break in ForEach-Object stops the pipeline” — it stops the enclosing loop or the whole script. ② “continue in ForEach-Object skips to the next object” — that is return. ③ “foreach after a pipe is the fast statement” — it is the alias of the slow-ish cmdlet. ④ “do { } while may run zero times” — it always runs once. ⑤ “A switch inside a loop: break leaves the loop” — it leaves only the switch. ⑥ “foreach streams” — the statement evaluates the whole collection first; for a 10 GB file use switch -File or Get-Content | ForEach-Object.

Diagram: where does break land?

script.ps1 (or the interactive command line) foreach ($round in 1..2) { … } ← nearest enclosing LOOP function Find-FirstProd { … } (no loop here) Import-Csv … | ForEach-Object { … break }the script block is called once per object; it is NOT a loopbreak searches outward: cmdlet → function → loop Result: “round 1, web-01, after rounds” — the function's last line and round 2 never run. No loop anywhere → the script ends; pwsh -File exits 0. Use Select-Object -First 1 or a foreach statement instead.
Figure 6-1: break/continue inside a script block unwind to the nearest loop on the call stack

Diagram: choosing a loop

foreach statementdata already in memoryfastest, break works$out = foreach (…) { } ForEach-Objectstreaming pipeline inputbig files, -Parallelstop with Select -First for / while / doindexes, polling, retriesdo runs at least oncealways add a timeout .Where() / .ForEach()in-memory, method syntax'First', 'Split' modesresult is a Collection
Figure 6-2: memory vs streaming decides between the statement and the cmdlet

Where does break land?

Choose a construct and step through it. Every outcome — including the lines that never run — was reproduced on 7.6.10.

Ready.

Command reference

SyntaxPurposeNotes
foreach ($x in $c) { }Loop over a collectionAssign output: $r = foreach …
$c | ForEach-Object { $_ }Process streamed objects-Begin, -Process, -End
for (init; cond; step) { }Counted loop$i++
while (c) { }, do { } while (c), do { } until (c)Condition loopsdo runs at least once
:name foreach …, break name, continue nameLabels for nested loopsLabel is a word after a colon, before the loop
.Where({ }, 'First', n), .ForEach({ }), .ForEach('Prop')Collection methodsIn-memory only
Select-Object -First nStop a pipeline earlyStops upstream commands
$servers = Import-Csv ./data/servers.csv
foreach ($s in $servers) { if ($s.Env -eq 'staging') { $s.Name } }
$servers | ForEach-Object { if ($_.Env -eq 'staging') { $_.Name } } | Select-Object -First 1
(Get-Command foreach).CommandType, (Get-Command foreach).Definition -join ' -> '
$(foreach ($s in 1..3) { $s }) | Measure-Object | Select-Object -ExpandProperty Count
for ($i = 0; $i -lt 3; $i++) { "i=$i" }
$lines = Get-Content ./data/access.log; $n = 0
while ($lines[$n] -notmatch '" 401 ') { $n++ }; "first 401 at line $($n + 1)"
$try = 5; do { $try++ } while ($try -lt 3); "do-while ran once: try=$try"
$try = 0; do { $try++ } until ($try -ge 3); "do-until: try=$try"
web-01
api-01
db-01
web-01
Alias -> ForEach-Object
3
i=0
i=1
i=2
first 401 at line 151
do-while ran once: try=6
do-until: try=3
# saved as a script file: the statement cannot be piped
foreach ($s in 1..3) { $s } | Measure-Object
ParserError: …\m6-pe.ps1:1
Line |
   1 |  foreach ($s in 1..3) { $s } | Measure-Object
     |                              ~
     | An empty pipe element is not allowed.

break, continue and return in script blocks

'--- return in ForEach-Object acts like continue'
1..5 | ForEach-Object { if ($_ % 2) { return }; "even $_" }
'--- break inside ForEach-Object inside a foreach loop'
foreach ($e in 'dev', 'staging') {
    "env $e"
    1..3 | ForEach-Object { if ($_ -eq 2) { break }; "  item $_" }
    "  end of $e"
}
'after outer loop'
'--- continue inside ForEach-Object inside a foreach loop'
foreach ($e in 'dev', 'staging') {
    1..3 | ForEach-Object { if ($_ -eq 2) { continue }; "  $e item $_" }
}
'--- break in switch inside foreach: only the switch'
foreach ($c in 200, 503, 404) { switch ($c) { 503 { 'found 503'; break } default { "saw $c" } } }
--- return in ForEach-Object acts like continue
even 2
even 4
--- break inside ForEach-Object inside a foreach loop
env dev
  item 1
after outer loop
--- continue inside ForEach-Object inside a foreach loop
  dev item 1
  staging item 1
--- break in switch inside foreach: only the switch
saw 200
found 503
saw 404

How to verify: look for the missing lines — “end of dev”, the whole staging round, and item 3 never appear. Common mistake: using break to mean “I found it, stop searching” inside ForEach-Object. Production use: Select-Object -First 1 for pipelines, foreach + break for loops.

Labels and collection methods

:outer foreach ($e in 'dev', 'staging', 'prod') {
    foreach ($r in 'web', 'api', 'db') {
        if ($e -eq 'staging' -and $r -eq 'api') { break outer }
        "$e/$r"
    }
}
(1..10).Where({ $_ % 3 -eq 0 }) -join ','
(1..10).Where({ $_ -gt 4 }, 'First', 2) -join ','
$small, $big = (1..10).Where({ $_ -le 5 }, 'Split'); "$($small -join ',') | $($big -join ',')"
(Import-Csv ./data/servers.csv).ForEach({ $_.Name.ToUpper() }) | Select-Object -First 3
Import-Csv ./data/servers.csv | Where-Object Env -eq 'prod' | Select-Object -First 1 -ExpandProperty Name
dev/web
dev/api
dev/db
staging/web
3,6,9
5,6
1,2,3,4,5 | 6,7,8,9,10
WEB-01
API-01
DB-01
web-01

Speed

$n = 100000
'foreach statement: {0} ms' -f [int](Measure-Command { $t = 0; foreach ($i in 1..$n) { $t += $i } }).TotalMilliseconds
'ForEach-Object:    {0} ms' -f [int](Measure-Command { $t = 0; 1..$n | ForEach-Object { $t += $_ } }).TotalMilliseconds
'.ForEach():        {0} ms' -f [int](Measure-Command { $t = 0; (1..$n).ForEach({ $t += $_ }) }).TotalMilliseconds
foreach statement: 136 ms
ForEach-Object:    721 ms
.ForEach():        308 ms

Goal: Reproduce a script that silently skips its last step because of break in ForEach-Object, observe the exit code, and fix it. Environment: pwsh 7.6 in ~/pslab. Cost: two small files in ~/pslab/scripts.

Write the buggy script ~/pslab/scripts/break-demo.ps1:
Set-Location ~/pslab
Set-Content ./scripts/break-demo.ps1 -Value @'
'start'
Import-Csv (Join-Path $PSScriptRoot '..' 'data' 'servers.csv') | ForEach-Object {
    if ($_.Env -eq 'prod') { "first prod: $($_.Name)"; break }
}
'end of script: summary written'
'@
Run it as a scheduler would — the last line is missing, yet the exit code is 0:
pwsh -NoProfile -File ./scripts/break-demo.ps1; "exit=$LASTEXITCODE"
start
first prod: web-01
exit=0
Call it from a loop — break crosses the script boundary and ends your loop:
foreach ($i in 1..3) { ./scripts/break-demo.ps1; "loop $i continues" }; 'after loop'
start
first prod: web-01
after loop

At the prompt, a line such as ./scripts/break-demo.ps1; 'same line' also loses everything after the script call on that line (verified with pwsh -Command).

Fix it with Select-Object -First 1 and run the loop again:
Set-Content ./scripts/break-fixed.ps1 -Value @'
'start'
$first = Import-Csv (Join-Path $PSScriptRoot '..' 'data' 'servers.csv') |
    Where-Object Env -eq 'prod' | Select-Object -First 1
"first prod: $($first.Name)"
'end of script: summary written'
'@
foreach ($i in 1..2) { ./scripts/break-fixed.ps1; "loop $i continues" }; 'after loop'
start
first prod: web-01
end of script: summary written
loop 1 continues
start
first prod: web-01
end of script: summary written
loop 2 continues
after loop
Cleanup: Remove-Item ./scripts/break-demo.ps1, ./scripts/break-fixed.ps1

Case 1: the backup that “succeeded” but never rotated

Problem: A backup script found the newest snapshot with Get-ChildItem … | Sort-Object LastWriteTime -Descending | ForEach-Object { $latest = $_; break }, then copied it and rotated old ones. Copies happened; rotation never did; the scheduler showed success for months until the disk filled. Root cause: with no enclosing loop, break ended the script right there, with exit code 0. Fix: $latest = … | Select-Object -First 1; add a final “completed” log line and alert when it is missing (Lesson 5).

Case 2: a module function broke the caller's loop

Problem: A helper Get-FirstHealthy used break inside ForEach-Object. When called from a deployment loop over regions, the deployment silently stopped after the first region. Root cause: break unwinds through the function to the caller's foreach. Fix: never use break/continue in script blocks; use return to skip one item and Select-Object -First to stop.

Case 3: a polling loop that never ended

Problem: while ((Get-Status) -ne 'Ready') { Start-Sleep 5 } ran for 14 hours when the resource failed. Root cause: no timeout and no failure state. Fix: $deadline = (Get-Date).AddMinutes(10); do { … } until ($s -in 'Ready','Failed' -or (Get-Date) -gt $deadline), then act on the final state.

Common errors and fixes

The script stops early but reports success

Cause: break or continue in a ForEach-Object/Where-Object script block with no enclosing loop.

Select-String -Path ./script.ps1 -Pattern '\b(break|continue)\b'

Fix: return to skip, Select-Object -First to stop, or convert to a foreach statement.

An empty pipe element is not allowed.

Cause: piping a foreach/for/while statement directly.

$(foreach ($x in $c) { $x }) | Sort-Object
$r = foreach ($x in $c) { $x }; $r | Sort-Object
$_ is empty inside a foreach statement

Cause: $_ belongs to pipelines and script blocks; the statement uses your loop variable.

Fix: use $s in foreach ($s in …).

Out of memory / very slow on a huge file

Cause: foreach ($l in Get-Content big.log) loads every line first.

Fix: stream: switch -File big.log { … } or Get-Content big.log -ReadCount 1000 | ForEach-Object { foreach ($l in $_) { … } }.

Command-line exercises
1. Find the first line number (1-based) whose status is 502, using a for loop and break.
$lines = Get-Content ~/pslab/data/access.log
for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '" 502 ') { $i + 1; break } }
458
2. Retry a flaky command at most 3 times with do/until (simulate failure for the first two tries).
$try = 0
do {
    $try++
    $ok = $try -ge 3          # pretend the third attempt succeeds
    "attempt $try ok=$ok"
} until ($ok -or $try -ge 3)
attempt 1 ok=False
attempt 2 ok=False
attempt 3 ok=True
Scenario analysis
A reviewer sees $items | ForEach-Object { if (-not $_.Enabled) { continue }; Process-Item $_ } in a function that is called inside a loop over tenants. What happens, and what should it be?

continue does not skip to the next item; it unwinds out of the function and continues the caller's tenant loop, so for the current tenant every item after the first disabled one is skipped silently. Replace it with return (skip this item), or filter first: $items | Where-Object Enabled | ForEach-Object { Process-Item $_ }. Add a test with a disabled item in the middle of the list.

Verified teaching videos

▶
How to use PowerShell foreach — Shane Young
English · the foreach statement for beginners
▶
PowerShell 7 Tutorials for Beginners #8 : ForEach (Loops) — JackedProgrammer
English · foreach vs ForEach-Object in PowerShell 7

No verified video demonstrates the break/continue behavior inside ForEach-Object; this module's animation and lab reproduce it.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: the word foreach splits into a keyword (statement) and an alias (cmdlet) depending on whether a pipe precedes it.
Narration: two things share one name. The statement loops over memory; the cmdlet streams.
Shot 2 · 20–55s
Visual: a break token inside a ForEach-Object block flies outward through a function box and lands on the outer loop, which collapses.
Narration: break inside a script block looks for the nearest loop — wherever it is.
Shot 3 · 55–75s
Visual: a scheduler shows green “exit 0” while the last line of the script is greyed out.
Narration: with no loop, the script just ends — and still exits zero.
Shot 4 · 75–90s
Visual: Select-Object -First 1 closes the tap upstream.
Narration: stop pipelines with Select-Object First; skip items with return.
or score ≥ 70% on the Quiz

Module 7 · Structured data: JSON (-Depth), CSV, PSD1 and XML

42:00 – 50:00 · JSON keeps numbers, booleans and nesting; CSV flattens everything to strings; PSD1 is PowerShell's safe configuration format; XML is still everywhere in Windows — and ConvertTo-Json silently flattens anything deeper than two levels unless you pass -Depth
8 minConvertTo-Json · Export-Csv · PSD1 · [xml]★★★★★
Learning objectives
  • Serialize with ConvertTo-Json and reproduce the default depth of 2 truncation (warning plus "System.Collections.Hashtable" strings); always pass -Depth.
  • Deserialize with ConvertFrom-Json (PSCustomObjects) or -AsHashtable (ordered hashtables), and know how dates and single-element arrays behave.
  • Compare inventory.json and servers.csv: JSON keeps types, CSV makes strings.
  • Write CSV with Export-Csv (no #TYPE line in 7.x, -UseQuotes AsNeeded, CRLF line endings on Windows).
  • Read configuration safely with Import-PowerShellDataFile, and navigate XML with [xml] and XPath.
Prerequisites: Modules 1, 4. Importance:★★★★★ (every API, pipeline and config file speaks one of these formats)

What: four formats, four trade-offs

FormatReadWriteTypes kept?NestingUse for
JSONConvertFrom-Json (-AsHashtable, -Depth, -DateKind)ConvertTo-Json -Depth nNumbers (Int64/Double), booleans, null, strings; ISO dates become DateTimeYesAPIs, reports, state files, CI artifacts
CSVImport-Csv, ConvertFrom-CsvExport-Csv, ConvertTo-CsvNo — every value is a stringNo (arrays are joined with spaces)Spreadsheets, flat inventories
PSD1Import-PowerShellDataFile(by hand)Yes (PowerShell literals)YesConfiguration, module manifests
XML[xml](Get-Content -Raw), Select-Xml$xml.Save(), ConvertTo-XmlNo — text nodes and attributes are stringsYesWindows configs, .csproj, RSS, legacy APIs

Why: ConvertTo-Json's depth trap

ConvertTo-Json walks an object graph and stops at depth 2 by default (maximum 100). Anything deeper is converted with .ToString(): a nested hashtable becomes the string "System.Collections.Hashtable". PowerShell 7.1+ prints a warning (“Resulting JSON is truncated as serialization has exceeded the set depth of 2”) — but a warning in a scheduled job is easy to miss, and the file is still written. Always pass -Depth sized to your data (the course uses 4–5). ConvertFrom-Json has a different default: -Depth 1024 for reading.

How: what comes back from ConvertFrom-Json

  • Objects become PSCustomObject (property order as in the file); with -AsHashtable an OrderedHashtable (7.3+) — faster, allows keys that differ only by case or are empty, and lets you test keys with .ContainsKey().
  • Numbers become Int64 (or Double/BigInteger), true/false become Boolean.
  • ISO-8601 strings become DateTime automatically; -DateKind String (7.5+) keeps them as text.
  • A top-level JSON array is enumerated into the pipeline in PowerShell 7 (12 objects for inventory.json); -NoEnumerate keeps it as one array. Windows PowerShell 5.1 sends it as one object.
  • Writing: a one-element array piped to ConvertTo-Json becomes a scalar (1, not [1]); use -InputObject @(…) or -AsArray.

When: CSV, PSD1 and XML details

  • CSV: PowerShell 7 writes no #TYPE header (-NoTypeInformation still exists and is the default); it quotes every field unless you pass -UseQuotes AsNeeded (or -QuoteFields); embedded commas are quoted correctly ("web,api"); on Windows lines end with CRLF, so a round trip of LF-only servers.csv has the same content but a different hash. Convert types when reading: Monitored -eq 'true', [int]$_.Port.
  • PSD1: Import-PowerShellDataFile accepts only literals (hashtables, arrays, strings, numbers, $true/$false/$null) and refuses expressions such as (Get-Date). Never dot-source or Invoke-Expression a config file. Remember that its hashtables are unordered (Module 4).
  • XML: [xml] parses text into an XmlDocument; elements and attributes appear as properties ($x.servers.server.name); use SelectNodes()/Select-Xml for XPath. Always read the file with -Raw.
Common misconceptions① “ConvertTo-Json serializes everything” — only 2 levels by default. ② “The warning means the file was not written” — it was written, with "System.Collections.Hashtable" in it. ③ “CSV preserves booleans” — Monitored comes back as "True"/"False" strings, and Where-Object Monitored keeps all 12 rows. ④ “Export-Csv needs -NoTypeInformation” — only in Windows PowerShell 5.1. ⑤ “A PSD1 is a script, so I can put Get-Date in it” — Import-PowerShellDataFile refuses dynamic expressions (by design). ⑥ “[xml]$text is safe for any input” — malformed XML throws; validate and catch.

Diagram: depth counting in ConvertTo-Json

$docdepth 0 Configdepth 1 Environmentsdepth 2 (the default limit) dev / staging / proddepth 3 → .ToString() Default (-Depth 2): "prod": "System.Collections.Hashtable" + WARNING: Resulting JSON is truncated …The file is still written — check for the string "System.Collections" in CI -Depth 5: "prod": { "HealthUrl": "https://shop.example.com/healthz", "RequireConfirm": true, … }Choose a depth larger than your deepest level; the maximum is 100
Figure 7-1: depth counts levels below the root; level 3 of the OpsKit config is the first one lost

Diagram: one server, two formats

inventory.json → ConvertFrom-JsonName : web-01 (String)Monitored : True (Boolean)Port : 8080 (Int64)Where-Object Monitored → 8 rows ✓ servers.csv → Import-CsvName : web-01 (String)Monitored : true (String!)no Port column; Role "web,api" stays one stringWhere-Object Monitored → 12 rows ✗
Figure 7-2: the same 12 servers; only JSON keeps the types (verified on 7.6.10)

JSON / CSV round-trip simulator

Pick a conversion and follow the data through serialization and back. Outcomes reproduced on 7.6.10.

Ready.

Command reference

CommandPurposeNotes
ConvertTo-Json -Depth 5 [-Compress] [-AsArray]Object → JSON textDefault depth 2!
Get-Content f -Raw | ConvertFrom-Json [-AsHashtable] [-NoEnumerate]JSON → objects-Raw reads one string
Import-Csv f [-Delimiter ';'] [-Header …]CSV → objects (strings)Handles quoted commas
Export-Csv f [-UseQuotes AsNeeded] [-Append] [-Encoding utf8BOM]Objects → CSV fileSelect properties first
Import-PowerShellDataFile f.psd1Safe config readLiterals only
[xml](Get-Content f -Raw), Select-Xml -XPathXML.SelectNodes(), .Save()
ConvertTo-Xml -As String -NoTypeInformationObjects → generic XMLRarely what an API wants
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
$doc = [ordered]@{ Name = 'OpsKit'; Config = [ordered]@{ Environments = $cfg.Environments } }
$doc | ConvertTo-Json
'--- with -Depth 5'
$doc | ConvertTo-Json -Depth 5 -Compress
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{
  "Name": "OpsKit",
  "Config": {
    "Environments": {
      "prod": "System.Collections.Hashtable",
      "dev": "System.Collections.Hashtable",
      "staging": "System.Collections.Hashtable"
    }
  }
}
--- with -Depth 5
{"Name":"OpsKit","Config":{"Environments":{"prod":{"HealthUrl":"https://shop.example.com/healthz","RequireConfirm":true,"Region":"canadacentral"},"dev":{"Region":"canadacentral","HealthUrl":"http://10.10.1.21:8080/healthz"},"staging":{"Region":"ca-central-1","HealthUrl":"http://10.20.1.31:8080/healthz"}}}}

How to verify: search the output for System.Collections or @{ — both mean an object was stringified. Common mistake: testing with a flat object, then adding one nested level in production. Production use: a CI check: if ((Get-Content out.json -Raw) -match 'System\.Collections|@\{') { exit 1 }.

JSON keeps types, CSV makes strings

$json = Get-Content ./data/inventory.json -Raw | ConvertFrom-Json
$csv  = Import-Csv ./data/servers.csv
$json[0].Monitored.GetType().Name, $json[0].Port.GetType().Name -join ' / '
$csv[0].Monitored.GetType().Name
($json | Where-Object Monitored).Count
($csv  | Where-Object Monitored).Count
($csv  | Where-Object Monitored -eq 'true').Count
(Get-Content ./data/inventory.json -Raw | ConvertFrom-Json | Measure-Object).Count
$ht = Get-Content ./data/inventory.json -Raw | ConvertFrom-Json -AsHashtable
$ht[0].GetType().Name; $ht[0].Keys -join ','; $ht[0]['Port'] + 1
('{"When":"2026-11-24T10:00:01Z"}' | ConvertFrom-Json).When.GetType().Name
('{"When":"2026-11-24T10:00:01Z"}' | ConvertFrom-Json -DateKind String).When.GetType().Name
Boolean / Int64
String
8
12
8
12
OrderedHashtable
Name,Env,Region,IP,Role,Monitored,Port
8081
DateTime
String
@(1) | ConvertTo-Json -Compress
ConvertTo-Json -InputObject @(1) -Compress
[ordered]@{ b = @(1, 2); a = 1 } | ConvertTo-Json -Compress
1
[1]
{"b":[1,2],"a":1}

CSV export

$prod = $json | Where-Object Env -eq 'prod' | Select-Object Name, Role, Monitored, Port
$prod | Export-Csv ./tmp/prod.csv
Get-Content ./tmp/prod.csv -TotalCount 2
$prod | Export-Csv ./tmp/prod.csv -UseQuotes AsNeeded
Get-Content ./tmp/prod.csv
(Import-Csv ./tmp/prod.csv)[0].Port.GetType().Name
$json | Select-Object -First 1 Name, @{ n = 'Tags'; e = { @('a', 'b') } } | ConvertTo-Csv
"Name","Role","Monitored","Port"
"web-01","web","True","8080"
Name,Role,Monitored,Port
web-01,web,True,8080
web-02,web,True,8080
api-01,api,True,8080
edge-01,"web,api",True,8080
db-01,db,False,8080
bastion-01,bastion,False,8080
String
"Name","Tags"
"web-01","a b"

No #TYPE line, quoting only where needed, the embedded comma handled — and the Int64 port is a string again after the round trip. Arrays are flattened with spaces ("a b"): join them explicitly (-join ';') or use JSON.

PSD1 safety and XML

Set-Content ./tmp/evil.psd1 -Value "@{ Name = 'x'; When = (Get-Date) }"
try { Import-PowerShellDataFile ./tmp/evil.psd1 } catch { $_.Exception.Message }
Set-Content ./tmp/servers.xml -Value @'
<servers env="prod">
  <server name="web-01" ip="10.30.1.41" monitored="true"><port>8080</port></server>
  <server name="db-01" ip="10.30.1.44" monitored="false"><port>5432</port></server>
</servers>
'@
[xml]$x = Get-Content ./tmp/servers.xml -Raw
$x.servers.env
$x.servers.server | Format-Table name, ip, monitored, port
$x.servers.server[1].port.GetType().Name
$x.SelectNodes('//server[@monitored="true"]').name
try { [xml]'<a><b></a>' } catch { $_.Exception.Message }
Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: @{ Name = 'x'; When = (Get-Date) }.
prod

name   ip         monitored port
----   --         --------- ----
web-01 10.30.1.41 true      8080
db-01  10.30.1.44 false     5432

String
web-01
Cannot convert value "<a><b></a>" to type "System.Xml.XmlDocument". Error: "The 'b' start tag on line 1 position 5 does not match the end tag of 'a'. Line 1, position 9."

Goal: Build a typed inventory from the CSV, export it to JSON with the right depth, and prove that a CSV round trip keeps content but not types or line endings. Environment: pwsh 7.6 in ~/pslab. Cost: a few files in ~/pslab/tmp.

Convert CSV strings into real types at the edge:
Set-Location ~/pslab
$typed = Import-Csv ./data/servers.csv | ForEach-Object {
    [pscustomobject]@{
        Name      = $_.Name
        Env       = $_.Env
        IP        = [ipaddress]$_.IP
        Roles     = @($_.Role -split ',')
        Monitored = [bool]::Parse($_.Monitored)
    }
}
($typed | Where-Object Monitored).Count
($typed | Where-Object { 'api' -in $_.Roles }).Name -join ','
8
api-01,api-01,api-01,edge-01
Export to JSON — with an [ipaddress] inside, the default depth shows the problem differently:
$typed[9] | ConvertTo-Json -Compress -WarningAction SilentlyContinue
$typed | Select-Object Name, Env, @{ n = 'IP'; e = { $_.IP.ToString() } }, Roles, Monitored |
    ConvertTo-Json -Depth 3 | Set-Content ./tmp/inventory-typed.json
(Get-Content ./tmp/inventory-typed.json -Raw | ConvertFrom-Json)[9] | Format-List
{"Name":"edge-01","Env":"prod","IP":{"AddressFamily":2,"ScopeId":null,"IsIPv6Multicast":false,"IsIPv6LinkLocal":false,"IsIPv6SiteLocal":false,"IsIPv6Teredo":false,"IsIPv6UniqueLocal":false,"IsIPv4MappedToIPv6":false,"Address":855776778},"Roles":["web","api"],"Monitored":true}

Name      : edge-01
Env       : prod
IP        : 10.30.2.51
Roles     : {web, api}
Monitored : True

.NET objects serialize as all of their properties — an IPAddress becomes a blob with Address: 855776778. Convert such values to strings for JSON.

CSV round trip: same content, different bytes:
Import-Csv ./data/servers.csv | Export-Csv ./tmp/copy.csv -UseQuotes AsNeeded
(Get-FileHash ./data/servers.csv).Hash -eq (Get-FileHash ./tmp/copy.csv).Hash
@(Compare-Object (Get-Content ./data/servers.csv) (Get-Content ./tmp/copy.csv)).Count
(Get-Item ./data/servers.csv).Length, (Get-Item ./tmp/copy.csv).Length -join ' vs '
False
0
600 vs 613

13 lines × 1 extra byte: Export-Csv wrote CRLF on Windows while the dataset uses LF. Compare content, not hashes, when files cross platforms (Lesson 4 covers encodings and line endings).

Cleanup: Remove-Item ./tmp/inventory-typed.json, ./tmp/copy.csv, ./tmp/prod.csv, ./tmp/evil.psd1, ./tmp/servers.xml -ErrorAction Ignore

Case 1: an ARM/Bicep parameter file full of “System.Collections.Hashtable”

Problem: A pipeline generated a deployment parameter file with $params | ConvertTo-Json | Set-Content params.json. The deployment failed with a type error on tags. Root cause: parameters → tags → value → {…} is deeper than 2; the tags became the string "System.Collections.Hashtable", and the warning was lost in the job log. Fix: ConvertTo-Json -Depth 10, a CI check for System.Collections, and $WarningPreference = 'Stop' in generation scripts if you want warnings to fail the job.

Case 2: everything was “monitored”

Problem: A compliance report from a CSV export showed 100% of servers monitored. Root cause: Where-Object Monitored on strings — "false" is truthy. Fix: convert at the edge ([bool]::Parse()), or switch the source to JSON where booleans stay booleans.

Case 3: a config file that ran code

Problem: A tool loaded settings.ps1 with dot-sourcing to read a hashtable. A contributor added a line that called a web endpoint, which then ran on every build agent. Root cause: configuration as executable code. Fix: use .psd1 + Import-PowerShellDataFile (refuses dynamic expressions) or JSON; review config changes like code anyway.

Common errors and fixes

WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.

Cause: the object is deeper than -Depth.

$obj | ConvertTo-Json -Depth 10
Conversion from JSON failed with error: Unexpected character encountered while parsing value / Unexpected end when deserializing object

Cause: the input is not complete JSON — read without -Raw and piped line by line in an old version, an HTML error page instead of JSON, a truncated file, or a BOM/encoding problem.

Get-Content f.json -Raw | ConvertFrom-Json
(Get-Content f.json -Raw).Substring(0, 80)
Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions.

Cause: a .psd1 contains an expression ((Get-Date), $env:X, a command).

Fix: keep data files literal; compute values in the script after loading.

ConvertFrom-Json: Cannot convert the JSON string because it contains keys with different casing

Cause: keys such as "id" and "Id" in one object; PSCustomObject properties are case-insensitive.

Fix: ConvertFrom-Json -AsHashtable.

Command-line exercises
1. Count unmonitored prod servers from inventory.json using its real booleans.
(Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json |
    Where-Object { $_.Env -eq 'prod' -and -not $_.Monitored }).Name -join ','
db-01,bastion-01
2. Read opskit.config.psd1 and print the backup settings as compact JSON.
(Import-PowerShellDataFile ~/pslab/data/opskit.config.psd1).Backup | ConvertTo-Json -Compress
{"Destination":"~/pslab/backups","Keep":7,"Exclude":["*.tmp",".cache"]}
Scenario analysis
A team exports cloud resources to CSV every night and diffs the files to detect changes. They get false positives on every run and miss changes inside tags. Propose a better design.

False positives: unordered hashtables produce different column/key orders, and line endings or quoting differ between machines. Missed changes: nested tags are flattened to System.Collections.Hashtable or space-joined strings in CSV. Better: export JSON with explicit property order ([ordered] or Select-Object list), sorted by a stable key, with -Depth large enough; compare objects (Compare-Object -Property Id, Hash, where Hash is computed from the canonical JSON of each resource) rather than text; keep CSV only as a human-friendly view.

Verified teaching videos

▶
PowerShell JSON Tutorial: ConvertFrom-Json & ConvertTo-Json Explained for Beginners — CodeLucky
English · JSON conversion basics
▶
PowerShell Master Class - Data and Objects — John Savill's Technical Training
English · parsing data and working with objects (CSV, JSON, XML)

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: the OpsKit config tree; at level 3 the branches turn into grey text “System.Collections.Hashtable”; a warning scrolls away.
Narration: ConvertTo-Json stops at depth two. Always pass Depth.
Shot 2 · 25–50s
Visual: the same server card from JSON (green types) and CSV (all grey strings).
Narration: JSON keeps numbers and booleans; CSV turns everything into text.
Shot 3 · 50–70s
Visual: a PSD1 with (Get-Date) bounces off Import-PowerShellDataFile.
Narration: data files contain data, not code.
Shot 4 · 70–90s
Visual: an XML tree; an XPath query highlights monitored servers.
Narration: XML becomes an object tree too — use XPath for queries.
or score ≥ 70% on the Quiz

Module 8 · Practice: an access-log analyzer that turns text into objects

50:00 – 60:00 · Put the hour together: one named-group regex, typed properties, a List for collection, hashtables and Group-Object for aggregation, an ordered report object, and JSON output — in a script with parameters, strict mode and exit codes
10 minGet-AccessLogReport.ps1★★★★★
Learning objectives
  • Write ~/pslab/scripts/Get-AccessLogReport.ps1: parse every line into a typed object, count the lines that do not match, and never drop data silently.
  • Produce a report with status counts (ordered by code), top clients, 5xx per path, the byte total and the time range — as an object by default, as JSON with -AsJson, or as raw records with -Records.
  • Apply the hour's rules: parse at the edge, $null-safe checks, List[T] instead of +=, [ordered] for stable output, -Depth for JSON, exit code 2 for missing input.
  • Use the interactive troubleshooting tree when a parser returns nothing or wrong numbers.
Prerequisites: Modules 1–7, Lesson 1 Module 8 (scripts, param(), exit codes). Importance:★★★★★ (Lesson 3 turns this logic into OpsKit functions)

What: the analyzer's contract

InputOutputExit code
-Path (default ../data/access.log relative to the script), -Top 1–100, -Records, -AsJsonOne report object (or JSON text, or one object per request); a warning if lines did not match0 on success, 2 if the log does not exist, 1 if PowerShell rejects a parameter (e.g. -Top 0)

Why: objects first, presentation last

The script does not print a table. It returns objects, so the caller decides: Format-Table at the prompt, -AsJson | Set-Content for a dashboard, -Records | Where-Object … for an investigation. This is Lesson 1's “format right” rule applied to your own tools — and the shape Lesson 3 will give OpsKit functions.

How: the pipeline inside the script

  1. Parse: foreach ($line in Get-Content …); if ($line -notmatch $pattern) { $unparsed++; continue }; build a [pscustomobject] with [int], [long] and ParseExact(…).ToUniversalTime(); $requests.Add() to a List[object].
  2. Aggregate: Group-Object Status sorted numerically into an [ordered] dictionary; .Where({ $_.Status -ge 500 }) for errors; Group-Object ClientIP sorted by count (then name, for a stable order); Measure-Object Bytes -Sum cast to [long].
  3. Report: one [pscustomobject] literal (property order fixed), arrays wrapped in @() so a single result is still a JSON array.
  4. Output: the object, or ConvertTo-Json -Depth 4.

When: what each module contributed

Line(s) in the scriptModule
[int]$Matches.status, [long], ParseExact, Set-StrictModeM1
$_.Status -ge 500, if ($unparsed), -notmatchM2
The named-group $pattern and $MatchesM3 (core)
List[object], [ordered]@{}, @(…)M4
if ($AsJson) … else …M5
foreach statement with continue (safe — it is a real loop)M6
ConvertTo-Json -Depth 4M7
Common misconceptions① “Unparsed lines can be ignored” — count and report them; a format change otherwise looks like a quiet day. ② “Group-Object sorts numerically” — group names are strings; sort with { [int]$_.Name }. ③ “Ties in top-N are stable” — sort by count and a second key. ④ “Measure-Object -Sum returns an integer” — it returns a Double; cast it. ⑤ “return $requests returns a List” — PowerShell enumerates it into the pipeline; that is what you want here. ⑥ “Local time is fine” — logs from several servers must be compared in UTC.

Data-flow diagram: Get-AccessLogReport.ps1

access.log611 lines of text -match $patternno match → $unparsed++ casts[int] [long] UTC DateTime List[object] of requests-Records returns these 611 objects StatusCountsGroup → [ordered] by code TopClientsGroup → sort count, name ServerErrorsByPath.Where(≥500) → Group Path TotalBytes · From · ToMeasure-Object [pscustomobject] reportdefault: object · -AsJson: ConvertTo-Json -Depth 4
Figure 8-1: text becomes objects once; every number in the report is computed from typed properties

Analyzer data flow

Choose a run and follow it from the command line to the exit code. All counts and messages are from real 7.6.10 runs.

Ready.

Interactive troubleshooting tree: my log parser gives wrong or no results

The script

Save as ~/pslab/scripts/Get-AccessLogReport.ps1:

<#
.SYNOPSIS
    Turns an nginx combined access log into typed objects and a summary report.
.DESCRIPTION
    Every line is parsed with one named-group regular expression into an object
    with typed properties (ClientIP, Time, Method, Path, Status, Bytes, UserAgent).
    The report contains status counts, top clients, 5xx responses per path and
    the byte total. Lines that do not match are counted, never silently dropped.
.PARAMETER Path
    The access log. Defaults to ../data/access.log relative to this script.
.PARAMETER Top
    Number of clients in TopClients (1-100).
.PARAMETER Records
    Output the parsed request objects instead of the report.
.PARAMETER AsJson
    Output the report as a JSON string.
.EXAMPLE
    ./Get-AccessLogReport.ps1 -Top 3
.EXAMPLE
    ./Get-AccessLogReport.ps1 -Records | Where-Object Status -ge 500
#>

#Requires -Version 7.4
[CmdletBinding()]
param(
    [string]$Path = (Join-Path $PSScriptRoot '..' 'data' 'access.log'),
    [ValidateRange(1, 100)][int]$Top = 5,
    [switch]$Records,
    [switch]$AsJson
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
    Write-Error "Get-AccessLogReport: log file not found: $Path" -ErrorAction Continue
    exit 2
}

# One regex, one named group per field. \S+ = "no spaces", [^"]* = "up to the next quote".
$pattern = '^(?<ip>\S+) \S+ \S+ \[(?<time>[^\]]+)\] "(?<method>[A-Z]+) (?<path>\S+) [^"]*" (?<status>\d{3}) (?<bytes>\d+) "[^"]*" "(?<ua>.*)"$'
$culture = [cultureinfo]::InvariantCulture
$requests = [System.Collections.Generic.List[object]]::new()
$unparsed = 0

foreach ($line in Get-Content -LiteralPath $Path) {
    if ($line -notmatch $pattern) { $unparsed++; continue }
    $requests.Add([pscustomobject]@{
        ClientIP  = $Matches.ip
        Time      = [datetime]::ParseExact($Matches.time, 'dd/MMM/yyyy:HH:mm:ss zzz', $culture).ToUniversalTime()
        Method    = $Matches.method
        Path      = $Matches.path
        Status    = [int]$Matches.status
        Bytes     = [long]$Matches.bytes
        UserAgent = $Matches.ua
    })
}
if ($unparsed) { Write-Warning "$unparsed line(s) did not match the log format" }
if ($Records) { return $requests }

$statusCounts = [ordered]@{}
foreach ($g in $requests | Group-Object Status | Sort-Object { [int]$_.Name }) {
    $statusCounts[$g.Name] = $g.Count
}
$byCount = @{ Expression = 'Count'; Descending = $true }, 'Name'
$errors  = $requests.Where({ $_.Status -ge 500 })

$report = [pscustomobject]@{
    Source             = Split-Path -Path $Path -Leaf
    Lines              = $requests.Count + $unparsed
    Parsed             = $requests.Count
    Unparsed           = $unparsed
    From               = ($requests | Measure-Object Time -Minimum).Minimum
    To                 = ($requests | Measure-Object Time -Maximum).Maximum
    StatusCounts       = $statusCounts
    ServerErrors       = $errors.Count
    ServerErrorsByPath = @($errors | Group-Object Path | Sort-Object $byCount | ForEach-Object {
                             [pscustomobject]@{ Path = $_.Name; Count = $_.Count
                                                Statuses = ($_.Group.Status | Sort-Object -Unique) -join ',' } })
    TopClients         = @($requests | Group-Object ClientIP | Sort-Object $byCount |
                             Select-Object -First $Top |
                             ForEach-Object { [pscustomobject]@{ ClientIP = $_.Name; Requests = $_.Count } })
    TotalBytes         = [long]($requests | Measure-Object Bytes -Sum).Sum
}
if ($AsJson) { $report | ConvertTo-Json -Depth 4 } else { $report }

Run it

Set-Location ~/pslab
./scripts/Get-AccessLogReport.ps1
Source             : access.log
Lines              : 611
Parsed             : 611
Unparsed           : 0
From               : 11/24/2026 10:00:01 AM
To                 : 11/24/2026 10:29:50 AM
StatusCounts       : {[200, 463], [201, 54], [301, 12], [302, 17]…}
ServerErrors       : 20
ServerErrorsByPath : {@{Path=/api/orders; Count=20; Statuses=500,502,503}}
TopClients         : {@{ClientIP=198.51.100.23; Requests=72}, @{ClientIP=203.0.113.7; Requests=66},
                     @{ClientIP=192.0.2.11; Requests=65}, @{ClientIP=172.16.5.4; Requests=64}…}
TotalBytes         : 2918056
(./scripts/Get-AccessLogReport.ps1 -Top 3).TopClients
ClientIP      Requests
--------      --------
198.51.100.23       72
203.0.113.7         66
192.0.2.11          65
$r = ./scripts/Get-AccessLogReport.ps1 -Records
$r.Count; $r[0].Status.GetType().Name; $r[0].Time.Kind
$r | Where-Object Status -ge 500 | Group-Object Status -NoElement | Format-Table Name, Count
$r | Where-Object { $_.Status -eq 502 } | Format-Table Time, ClientIP, Path, Status
611
Int32
Utc

Name Count
---- -----
500      8
502      4
503      8

Time                   ClientIP   Path        Status
----                   --------   ----        ------
11/24/2026 10:21:58 AM 10.20.1.31 /api/orders    502
11/24/2026 10:21:59 AM 10.20.1.31 /api/orders    502
11/24/2026 10:22:00 AM 10.20.1.31 /api/orders    502
11/24/2026 10:22:01 AM 10.20.1.31 /api/orders    502

How to verify: 20 errors, 72 requests from 198.51.100.23 and 2,918,056 bytes match the dataset facts; the four 502s are lines 458–461 from the staging web server (Module 4's lookup). Common mistake: formatting inside the script. Production use: -Records is the investigation mode; the report is the monitoring mode.

./scripts/Get-AccessLogReport.ps1 -AsJson -Top 2 | Set-Content ./tmp/report.json
(Get-Content ./tmp/report.json -Raw | ConvertFrom-Json).StatusCounts.'503'
Get-Content ./tmp/report.json -TotalCount 8
8
{
  "Source": "access.log",
  "Lines": 611,
  "Parsed": 611,
  "Unparsed": 0,
  "From": "2026-11-24T10:00:01Z",
  "To": "2026-11-24T10:29:50Z",
  "StatusCounts": {

UTC DateTime values serialize as ISO-8601 with Z. Property names that are numbers need quotes in PowerShell: .StatusCounts.'503'.

Failure paths

./scripts/Get-AccessLogReport.ps1 -Path ./nope.log; "exit=$LASTEXITCODE"
Copy-Item ./data/access.log ./tmp/broken.log; Add-Content ./tmp/broken.log 'garbage line from a log rotation'
./scripts/Get-AccessLogReport.ps1 -Path ./tmp/broken.log | Format-List Lines, Parsed, Unparsed, ServerErrors
./scripts/Get-AccessLogReport.ps1 -Top 0
Write-Error: Get-AccessLogReport: log file not found: ./nope.log
exit=2
WARNING: 1 line(s) did not match the log format

Lines        : 612
Parsed       : 611
Unparsed     : 1
ServerErrors : 20

Get-AccessLogReport.ps1: Cannot validate argument on parameter 'Top'. 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.

Goal: Build the analyzer step by step and use it for two investigations. Environment: pwsh 7.6 in ~/pslab. Cost: ~/pslab/scripts/Get-AccessLogReport.ps1 (kept for Lesson 3) and files in ~/pslab/tmp.

Create the script from the Commands tab in VS Code (code ~/pslab/scripts/Get-AccessLogReport.ps1), save it, and check its help:
Get-Help ./scripts/Get-AccessLogReport.ps1 -Examples | Select-Object -ExpandProperty examples | Out-String -Width 80
-------------------------- EXAMPLE 1 --------------------------
PS > ./Get-AccessLogReport.ps1 -Top 3
-------------------------- EXAMPLE 2 --------------------------
PS > ./Get-AccessLogReport.ps1 -Records | Where-Object Status -ge 500

Found while writing this lesson: without the blank line between #> and #Requires, the help parser appended the #Requires comment to the last example — 7.6.10 printed Requires -Version 7.4 under EXAMPLE 2. Keep a blank line after the help block.

Check it against the dataset facts:
$rep = ./scripts/Get-AccessLogReport.ps1
$rep.ServerErrors -eq 20 -and $rep.TopClients[0].ClientIP -eq '198.51.100.23' -and $rep.TotalBytes -eq 2918056
True
Investigation 1 — the brute-force attempt: who caused the 401s, when, and from which tool?
./scripts/Get-AccessLogReport.ps1 -Records | Where-Object Status -eq 401 |
    Group-Object ClientIP, UserAgent -NoElement | Format-Table Count, Name -AutoSize
Count Name
----- ----
    6 198.51.100.23, python-requests/2.32.5
Investigation 2 — error rate per minute for the API:
./scripts/Get-AccessLogReport.ps1 -Records | Where-Object Path -like '/api/orders*' |
    Group-Object { $_.Time.ToString('HH:mm') } | Where-Object { $_.Group.Status -ge 500 } |
    Select-Object Name, Count, @{ n = 'Errors'; e = { @($_.Group.Status -ge 500).Count } } |
    Sort-Object Errors -Descending | Select-Object -First 3
Name  Count Errors
----  ----- ------
10:09    13      3
10:21    13      2
10:22     6      2

$_.Group.Status -ge 500 combines member enumeration (M4) and an array on the left (M2): it returns the error codes of that minute. The four 502s from 10.20.1.31 straddle 10:21 and 10:22 (10:21:58 – 10:22:01), so per-minute bucketing splits the incident in two — a reason to look at sliding windows, not only fixed buckets.

Cleanup: Remove-Item ./tmp/report.json, ./tmp/broken.log -ErrorAction Ignore. Keep the script.

Case 1: the quiet day that was a format change

Problem: After a load-balancer upgrade, the nightly error report showed zero errors for a week. Root cause: the new log format added a field; the parser's regex no longer matched and the old script skipped non-matching lines without counting them. Fix: count unparsed lines, emit a warning, and fail (exit 1) when more than a small percentage do not match; keep sample lines of every format as tests.

Case 2: wrong peak hour after daylight saving time

Problem: A traffic report shifted by one hour twice a year and disagreed with the CDN dashboard. Root cause: timestamps were parsed into local time and grouped by local hour. Fix: parse with the offset (zzz) and convert to UTC immediately (.ToUniversalTime()); convert to local time only for display.

Case 3: a JSON report that broke the dashboard on quiet days

Problem: The dashboard expected ServerErrorsByPath to be an array; on days with errors on only one path it received an object and crashed. Root cause: one result is not an array, and ConvertTo-Json writes what it gets. Fix: wrap collections in @( … ) in the report (as this script does) and add a schema test for one-element and zero-element cases.

Common errors and fixes

Every line counts as unparsed

Cause: the format differs from the pattern (extra field, different date format, tabs), or the regex has a typo.

$l = Get-Content $log -TotalCount 1
$l -match '^(?<ip>\S+) '                       # grow the pattern piece by piece
$l -match '^(?<ip>\S+) \S+ \S+ \[(?<time>[^\]]+)\] '

Fix: build the pattern incrementally against a real line; use the troubleshooting tree above.

Exception calling "ParseExact" with "3" argument(s): "String '…' was not recognized as a valid DateTime."

Cause: the format string does not fit, or the current culture's month names are used.

Fix: [cultureinfo]::InvariantCulture, and print $Matches.time to compare with the format.

The property 'X' cannot be found on this object (strict mode)

Cause: a misspelled property in the report, or reading a group that does not exist under Set-StrictMode -Version Latest.

Fix: correct the name; for optional data use $h['key'] or .ContainsKey() (Module 4).

Top clients change order between runs

Cause: ties in Count with no second sort key, or grouping into an unordered hashtable.

Fix: Sort-Object @{ Expression = 'Count'; Descending = $true }, Name.

Command-line exercises
1. Using -Records, list total bytes per path, largest first, formatted in KB.
./scripts/Get-AccessLogReport.ps1 -Records | Group-Object Path |
    Select-Object Name, @{ n = 'KB'; e = { [math]::Round(($_.Group | Measure-Object Bytes -Sum).Sum / 1KB, 1) } } |
    Sort-Object KB -Descending | Select-Object -First 3
Name                KB
----                --
/static/app.js 2118.70
/api/orders     392.10
/               255.50
2. Add a MethodCounts property to your own copy of the report without editing the script.
$rep = ./scripts/Get-AccessLogReport.ps1
$m = [ordered]@{}; ./scripts/Get-AccessLogReport.ps1 -Records | Group-Object Method | ForEach-Object { $m[$_.Name] = $_.Count }
$rep | Add-Member -NotePropertyName MethodCounts -NotePropertyValue $m -PassThru | Select-Object -ExpandProperty MethodCounts
Name                           Value
----                           -----
GET                            526
POST                           85
Scenario analysis
The analyzer must now process 30 GB of logs per day from 40 servers. What would you change first, and what would you keep?

Keep: one regex with named groups, typed properties, UTC times, unparsed counting, objects-first output and JSON with explicit depth. Change: stream instead of collecting all requests in memory — aggregate on the fly with hashtable counters (status, client, path) inside a switch -Regex -File or Get-Content -ReadCount loop, and keep raw records only on demand; process servers in parallel (ForEach-Object -Parallel, Lesson 6) and merge the partial counters; consider a compiled [regex] instance with RegexOptions.Compiled; and at that scale evaluate a log platform rather than a script. Prove each change with Measure-Command on a fixed sample and compare reports for equality.

Verified teaching videos

▶
PowerShell Master Class - Data and Objects — John Savill's Technical Training
English · parsing data into objects
▶
POWERSHELL TUTORIAL REGEX, MATCH AND REPLACE [Highway to PowerShell - Episode 8] — Simon Automates
English · regex extraction used by the analyzer

No verified video builds an access-log analyzer of this shape; the script in this module is the reference.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: 611 grey text lines pour into a regex funnel and come out as coloured object cards.
Narration: parse once, at the edge, into typed objects.
Shot 2 · 20–50s
Visual: the cards sort themselves into four bins: status, clients, 5xx per path, bytes.
Narration: group, count and measure — on properties, never on column numbers.
Shot 3 · 50–75s
Visual: the report object turns into JSON; a garbage line raises a yellow warning and Unparsed becomes 1.
Narration: never drop data silently. Count what you could not parse.
Shot 4 · 75–90s
Visual: a missing file returns exit code 2 to a scheduler.
Narration: objects for people and tools, exit codes for schedulers.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 2 key points: types and conversion, operators, regex, collections, switch, loops, structured data and the analyzer pattern
PowerShell 7.6Copyable

1. Types and $null

$x.GetType().FullName
[int]'42'; [long]'48213'; [int]2.5      # 2 (banker's rounding)
[datetime]::ParseExact($s, 'dd/MMM/yyyy:HH:mm:ss zzz', [cultureinfo]::InvariantCulture)
[version]'7.6.10' -gt [version]'7.10.0' # False (correct)
'10.0.0.999' -as [ipaddress]            # $null, no error
"10" + 5  →  105      5 + "10"  →  15   # left operand decides
$null -eq $x                            # $null on the LEFT
[int]$n = '7'                           # typed variable
Set-StrictMode -Version Latest

2. Operators

'PROD' -eq 'prod'; 'PROD' -ceq 'prod'   # True / False
200,404,503 -ge 500                     # 503  (array left = filter)
@($codes -ne 200).Count -gt 0           # "any" written explicitly
'web-01' -like 'web-*'; $s -match '^web-\d+$'
'api' -in ($role -split ',');  $list -contains 'api'
'{0,-10}{1,8:N0}' -f $name, $bytes
$c -gt 0 ? 'ALERT' : 'OK'
$cfg.LogLevel ?? 'Information'; $cfg.Timeout ??= 5
${s}?.Length                            # braces required
Test-Path $p && 'yes';  cmd || 'failed'

3. Regex and strings

if ($line -match '" (?<status>\d{3}) ') { [int]$Matches.status }
'web-01' -replace '-(\d+)', '_$1'        # single quotes!
'x' -replace 'pat', { $_.Value.ToUpper() }
'a.b' -replace '\.', '-';  'a.b'.Replace('.', '-')
$s -split '\s+';  -split $s;  $s -split ',', 2
$a -join ', '
[regex]::Matches($s, '\d+').Value
Select-String -Path f -Pattern p -AllMatches -CaseSensitive
[regex]::Escape($userText)

4. Collections

$a = @(cmd)                              # always an array
$out = foreach ($i in $items) { $i }     # instead of +=
$l = [System.Collections.Generic.List[object]]::new(); $l.Add($x)
$h = @{}; $h[$k]++                       # counter
$byIp = @{}; foreach ($s in $servers) { $byIp[$s.IP] = $s }
$o = [ordered]@{ dev = 1; prod = 2 }     # stable order
$servers.Name                            # member enumeration
(Get-ChildItem -File).ForEach('Length')  # when .Length is ambiguous
[pscustomobject]@{ Name = 'x'; Port = 8080 }
Get-Content @params                      # splatting

5. if and switch

$v = if ($n -gt 600) { 'big' } else { 'small' }
switch ($x) { 404 { …; break } { $_ -ge 400 } { … } default { … } }
switch -Wildcard ($names) { 'web-*' { …; continue } }
switch -Regex -File ./data/access.log { '" 5\d\d ' { $n5++; continue } }
switch -CaseSensitive ($v) { … }
# falsy: $false $null 0 '' @() @(0) · truthy: 'false' '0' @(0,0)

6. Loops

foreach ($s in $servers) { if (…) { break } }   # statement: break OK
$servers | ForEach-Object { if (…) { return } }  # return = skip item
… | Select-Object -First 1                       # stop a pipeline
for ($i = 0; $i -lt $n; $i++) { }
do { … } until ($ok -or $try -ge 3)
:outer foreach (…) { foreach (…) { break outer } }
$c.Where({ $_ -gt 4 }, 'First', 2); $c.ForEach({ … })
# NEVER: break/continue inside ForEach-Object / Where-Object

7. Structured data

$o | ConvertTo-Json -Depth 5            # default depth is 2!
Get-Content f.json -Raw | ConvertFrom-Json [-AsHashtable]
ConvertTo-Json -InputObject @($one)     # keep a 1-element array
Import-Csv f.csv                        # all strings
$x | Select-Object A, B | Export-Csv f.csv -UseQuotes AsNeeded
Import-PowerShellDataFile cfg.psd1      # literals only, safe
[xml]$x = Get-Content f.xml -Raw; $x.SelectNodes('//server')

8. Analyzer pattern

Set-StrictMode -Version Latest
$req = [System.Collections.Generic.List[object]]::new(); $bad = 0
foreach ($line in Get-Content -LiteralPath $Path) {
    if ($line -notmatch $pattern) { $bad++; continue }
    $req.Add([pscustomobject]@{ Status = [int]$Matches.status; … })
}
if ($bad) { Write-Warning "$bad line(s) did not match" }
[pscustomobject]@{ … } | ConvertTo-Json -Depth 4
exit 2   # input missing · 1 check failed · 0 ok

Integrated lab + final quiz

Turn access.log into a JSON summary with Get-AccessLogReport.ps1, then write ~/pslab/Test-AccessLogSummary.ps1 that validates the summary with independent cross-checks and returns exit codes 0 / 1 / 2
about 25 minLocal onlyIntegrates M1–M8

Scenario

A dashboard team will consume a nightly access-summary.json. Before it is published, a validation step must prove the file is complete and internally consistent: required properties exist, counts add up, the number of 5xx responses matches an independent count from the raw log, the top-client list is sorted, and numbers are real numbers. The validator outputs one result object per check, saves them to ~/pslab/tmp/Test-AccessLogSummary.json, exits 0 when everything passes, 1 when any check fails (with a warning naming the failed checks) and 2 when the summary is missing or is not valid JSON — the same contract as Lesson 1's Test-LabData.ps1.

Produce the summary (M8):
Set-Location ~/pslab
./scripts/Get-AccessLogReport.ps1 -AsJson | Set-Content ./tmp/access-summary.json
The validator (M1 types, M2 operators, M3 regex, M4 collections, M5 conditions, M7 JSON) — save as ~/pslab/Test-AccessLogSummary.ps1:
<#
.SYNOPSIS
    Validates the JSON summary written by scripts/Get-AccessLogReport.ps1.
.DESCRIPTION
    Outputs one result object per check and saves them to tmp/Test-AccessLogSummary.json.
    Exit codes: 0 = all checks passed, 1 = at least one check failed,
    2 = the summary file is missing or is not valid JSON.
.PARAMETER SummaryPath
    The JSON summary to validate.
.PARAMETER LogPath
    The original access log, used for independent cross-checks.
.EXAMPLE
    ./Test-AccessLogSummary.ps1 -SummaryPath ./tmp/access-summary.json
#>

#Requires -Version 7.4
[CmdletBinding()]
param(
    [string]$SummaryPath = (Join-Path $PSScriptRoot 'tmp' 'access-summary.json'),
    [string]$LogPath     = (Join-Path $PSScriptRoot 'data' 'access.log')
)
Set-StrictMode -Version Latest

if (-not (Test-Path -LiteralPath $SummaryPath -PathType Leaf)) {
    Write-Error "Test-AccessLogSummary: summary not found: $SummaryPath" -ErrorAction Continue
    exit 2
}
try {
    $s = Get-Content -LiteralPath $SummaryPath -Raw | ConvertFrom-Json -AsHashtable -ErrorAction Stop
} catch {
    Write-Error "Test-AccessLogSummary: not valid JSON: $($_.Exception.Message)" -ErrorAction Continue
    exit 2
}

$required = 'Source', 'Lines', 'Parsed', 'Unparsed', 'StatusCounts', 'ServerErrors',
            'ServerErrorsByPath', 'TopClients', 'TotalBytes'
$missing  = @($required | Where-Object { -not $s.ContainsKey($_) })

function New-Check([string]$Check, $Expected, $Actual) {
    [pscustomobject]@{ Check = $Check; Expected = $Expected; Actual = $Actual; Passed = $Expected -eq $Actual }
}

$results = @(
    New-Check 'required properties' 'none missing' ($missing ? ($missing -join ',') : 'none missing')
)
if (-not $missing) {
    $logLines = @(Get-Content -LiteralPath $LogPath)
    $fiveXX   = @($logLines -match '" 5\d\d ').Count
    $statusSum = ($s.StatusCounts.Values | Measure-Object -Sum).Sum
    $fromCodes = ($s.StatusCounts.GetEnumerator() | Where-Object { [int]$_.Key -ge 500 } |
                  Measure-Object -Property Value -Sum).Sum
    $counts    = @($s.TopClients | ForEach-Object { $_.Requests })
    $results += @(
        New-Check 'lines = log lines'            $logLines.Count  $s.Lines
        New-Check 'parsed + unparsed = lines'    $s.Lines         ($s.Parsed + $s.Unparsed)
        New-Check 'status counts sum = parsed'   $s.Parsed        ([int]$statusSum)
        New-Check '5xx = log lines with 5xx'     $fiveXX          $s.ServerErrors
        New-Check '5xx = sum of 5xx codes'       $s.ServerErrors  ([int]$fromCodes)
        New-Check '5xx by path adds up'          $s.ServerErrors  ([int]($s.ServerErrorsByPath | Measure-Object Count -Sum).Sum)
        New-Check 'top clients sorted'           (($counts | Sort-Object -Descending) -join ',') ($counts -join ',')
        New-Check 'TotalBytes is an integer'     'Int64'          $s.TotalBytes.GetType().Name
    )
}

$out = Join-Path $PSScriptRoot 'tmp' 'Test-AccessLogSummary.json'
$results | ConvertTo-Json | Set-Content -LiteralPath $out
$results

$failed = @($results | Where-Object { -not $_.Passed })
if ($failed) {
    Write-Warning "$($failed.Count) check(s) failed: $($failed.Check -join '; ')"
    exit 1
}
exit 0

Design notes: -AsHashtable makes “is this key present?” a reliable .ContainsKey() test even under strict mode; the 5xx cross-check counts the raw log with a different method (array-on-the-left -match, M2) than the analyzer (named-group regex) — two implementations agreeing is stronger evidence than one; Expected -eq Actual compares with the left operand's type, so both sides are cast to [int] where sums return Double.

Run it:
./Test-AccessLogSummary.ps1 | Format-Table; "exit=$LASTEXITCODE"
Check                      Expected       Actual         Passed
-----                      --------       ------         ------
required properties        none missing   none missing     True
lines = log lines          611            611              True
parsed + unparsed = lines  611            611              True
status counts sum = parsed 611            611              True
5xx = log lines with 5xx   20             20               True
5xx = sum of 5xx codes     20             20               True
5xx by path adds up        20             20               True
top clients sorted         72,66,65,64,62 72,66,65,64,62   True
TotalBytes is an integer   Int64          Int64            True

exit=0
Tamper with the summary and check the failure path:
$j = Get-Content ./tmp/access-summary.json -Raw | ConvertFrom-Json
$j.ServerErrors = 19
$j | ConvertTo-Json -Depth 4 | Set-Content ./tmp/bad-summary.json
./Test-AccessLogSummary.ps1 -SummaryPath ./tmp/bad-summary.json | Where-Object { -not $_.Passed } | Format-Table; "exit=$LASTEXITCODE"
WARNING: 3 check(s) failed: 5xx = log lines with 5xx; 5xx = sum of 5xx codes; 5xx by path adds up
Check                    Expected Actual Passed
-----                    -------- ------ ------
5xx = log lines with 5xx       20     19  False
5xx = sum of 5xx codes         19     20  False
5xx by path adds up            19     20  False

exit=1

One wrong number is caught by three independent checks. Note the -Depth 4 when writing the tampered file back. For this report the default depth 2 happens to be just enough (verified: no stringified objects, no extra failures) — one more nesting level in the report and it would not be. Always state the depth.

Missing, broken and incomplete input:
pwsh -NoProfile -NonInteractive -File ./Test-AccessLogSummary.ps1 | Out-Null; "exit=$LASTEXITCODE"
./Test-AccessLogSummary.ps1 -SummaryPath ./tmp/nope.json; "exit=$LASTEXITCODE"
'{ "Lines": 611, ' | Set-Content ./tmp/broken.json
./Test-AccessLogSummary.ps1 -SummaryPath ./tmp/broken.json; "exit=$LASTEXITCODE"
'{ "Lines": 611 }' | Set-Content ./tmp/partial.json
./Test-AccessLogSummary.ps1 -SummaryPath ./tmp/partial.json | Format-List Check, Actual, Passed; "exit=$LASTEXITCODE"
exit=0
Write-Error: Test-AccessLogSummary: summary not found: ./tmp/nope.json
exit=2
Write-Error: Test-AccessLogSummary: not valid JSON: Conversion from JSON failed with error: Unexpected end when deserializing object. Path 'Lines', line 3, position 0.
exit=2

Check  : required properties
Actual : Source,Parsed,Unparsed,StatusCounts,ServerErrors,ServerErrorsByPath,TopClients,TotalBytes
Passed : False

WARNING: 1 check(s) failed: required properties
exit=1
Acceptance criteria
Cleanup: Remove-Item ./tmp/bad-summary.json, ./tmp/broken.json, ./tmp/partial.json -ErrorAction Ignore. Keep scripts/Get-AccessLogReport.ps1 for Lesson 3.

Open-ended self-check

1. Explain, with the access log, why if ($statuses -eq 500) is not a reliable “is there a 500?” test, and give two correct alternatives.

With an array on the left, -eq returns the matching elements; the if then judges their truthiness. Here 500 is truthy so it happens to work, but the same pattern with -eq 0, with $null, or with -ne and exactly one match gives wrong answers. Use $statuses -contains 500 or @($statuses -eq 500).Count -gt 0.

2. Your parser reads line 307 correctly, but your colleague's -split ' ' version reports its User-Agent as +https://example.com/bot)". Why, and what general rule does it illustrate?

The User-Agent contains spaces, so splitting gives 15 fields instead of 12 and $f[-1] is only the last fragment. The status still happens to be $f[8] because it comes before the User-Agent — a fragile coincidence. Describe the structure (regex with quoted parts, or a real CSV/JSON parser) instead of counting positions; convert to objects once and work with property names.

3. A script uses break inside ForEach-Object. Describe what happens when it is run (a) by pwsh -File, (b) from a loop in another script.

(a) The script ends at the break; the remaining statements do not run; the exit code is still 0. (b) The break unwinds through the script and ends the caller's loop. Use Select-Object -First or a foreach statement.

4. Why might two runs of the same script produce JSON with different key orders, and how do you make the output stable?

Plain hashtables (including those from Import-PowerShellDataFile) have no defined order, and in PowerShell 7 string hashing is randomized per process. Use [ordered] dictionaries or [pscustomobject] literals, sort keys explicitly, and compare objects rather than text.

Sources and version notes

Facts were checked on 2026-11-24 against Microsoft Learn and YouTube oEmbed; every “Actual output” was produced on PowerShell 7.6.10 (.NET 10.0.15, Windows 11, culture en-US) with the course dataset
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Types and conversionLeft operand decides ("10"+5 = 105, 5+"10" = 15, "5.0" -eq 5 False); [int] rounds half to even; literal types; typed variablesabout_Type_Conversion; about_Type_Accelerators; about_Numeric_Literals; this lesson's runs
$null and automatic variables$null on the left; $?, $LASTEXITCODE, $Matches, $args; strict mode errors for unset variables, missing properties and missing hashtable keys accessed with dot notationEverything about $null; about_Automatic_Variables; Set-StrictMode
OperatorsCollection on the left filters; case-insensitive defaults; -contains/-in; -f; ?:, ??, ??=, ?. (braces needed — $s?.Length reads variable s?, verified); &&/||about_Comparison_Operators; about_Operators; about_Pipeline_Chain_Operators; about_Logical_Operators
Regular expressions$Matches not cleared on failure and not set for array input; -replace with $1, ${name}, script blocks; -split options; Select-String case-insensitive by defaultabout_Regular_Expressions; about_Split; about_Join; Select-String
Collections+= measured (10k ≈ 95 ms, 40k ≈ 5,200 ms) vs List.Add and assigned loop output; hashtable key order differs between processes; member enumeration vs the collection's own .LengthEverything about arrays; Everything about hashtables; about_Member-Access_Enumeration; Scripting performance considerations; about_Splatting
Conditionalsswitch runs all matching clauses; default only when nothing matched; empty input runs nothing; -File treats the path as a wildcard and has no -LiteralPathabout_Switch; about_If; about_Booleans
Loopsbreak inside ForEach-Object ends the enclosing loop, the caller's loop (through functions and scripts), or the script with exit code 0; return skips one itemabout_Break; about_Continue; about_Foreach; ForEach-Object
Structured dataConvertTo-Json default depth 2 with warning; ConvertFrom-Json -AsHashtable → OrderedHashtable (7.3+); -DateKind (7.5+); Export-Csv -UseQuotes, no #TYPE in 7.x, CRLF on Windows; Import-PowerShellDataFile rejects dynamic expressionsConvertTo-Json; ConvertFrom-Json; Export-Csv; Import-PowerShellDataFile
Comment-based helpA #Requires line directly after #> was appended to the last .EXAMPLE by Get-Help on 7.6.10; a blank line fixes itThis lesson's runs; about_Scripts
Sample datasetSame SHA-256 prefixes as Lesson 1; analyzer totals 611 lines, 20 × 5xx, top client 198.51.100.23 (72), 2,918,056 bytesActual runs for this lesson

Video verification notes

Only videos whose titles and channels were checked via YouTube oEmbed on 2026-11-24 are listed:

oEmbed verifies titles and channels only; the videos were not watched segment by segment, and the descriptions are based on titles. Several use Windows PowerShell 5.1 or older PowerShell 7 releases; where behavior differs, this lesson is authoritative. No verified video was found that covers the collection-on-the-left behavior, the ?. brace requirement, break inside ForEach-Object, or the ConvertTo-Json depth warning specifically.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API (en-US); it needs no network access or external scripts. The narration scripts and storyboards can be passed to a TTS or video tool.

Known limitations

  • Run environment: all “Actual output (7.6.10)” blocks were produced on Windows 11 with PowerShell 7.6.10 in a scratch copy of ~/pslab; paths were shortened. Dates are shown in the en-US format; your culture may format them differently. Not run on Linux or macOS: cmd /c exit 3 examples are Windows-only (use sh -c 'exit 3'), and Export-Csv writes LF there, so the CSV round-trip hash may match on Unix.
  • Timings (+=, loop speeds) depend on hardware and load; the ratios are the point. Hashtable key orders differ on every run by design.
  • The animations simplify the engine: they do not show the binder's full conversion order, regex backtracking, or how break/continue are implemented internally (as exceptions that unwind the call stack).
  • The Get-Help / #Requires observation was reproduced on 7.6.10 only; Lesson 1's Test-LabData.ps1 has the same layout and shows the same symptom in Get-Help -Examples.
  • Statements about Windows PowerShell 5.1 (no ternary/null operators, #TYPE lines, ConvertFrom-Json not enumerating arrays) come from the documentation and were not re-run for this lesson.