PowerShell Hour 9 (optional): 50 Production Issues + 50 Interview Questions

Two skills. In production: when a PowerShell job fails — or worse, “succeeds” with the wrong result — recognize which layer the fault sits in (pipeline and parsing, language and data, errors and concurrency, modules / CI / security) and type the first diagnostic command. In an interview: explain in two minutes how the engine parses, binds and streams objects, and review a flawed script on the spot
A: 50 production issuesB: 50 interview questionsPowerShell 7.6 LTS (7.6.10) · 5.1 notesVerified · 2026-11-24
Position in the Learning Path Hours 1–8 built the skills one layer at a time: the engine and pipeline (Hour 1), language essentials (2), advanced functions and OpsKit v0.1 (3), the module and PSResourceGet (4, v0.2), errors and safe change (5, v0.3 Invoke-OpsBackup), remoting and parallelism (6, v0.4 Invoke-OpsHealthCheck), cloud and API automation (7, v0.5 Invoke-OpsApi, Get-OpsCloudInventory) and testing and release (8, OpsKit v1.0). This optional hour turns that knowledge around: start from the symptom and work back to the mechanism, then start from the interviewer's question and show the mechanism with code. The milestone for this hour is not a new OpsKit version but a failure-ready OpsKit: every issue below maps to a test, an analyzer rule or a coding rule you can add to the v1.0 repository.
Overall Learning Objectives
  • Given a raw message (ClassId2e4f51ef… in a CSV, Resulting JSON is truncated, is not recognized as a name of a cmdlet, Deserialized.System.IO.FileInfo does not contain a method, NativeCommandExitException, HttpClient.Timeout of 2 seconds elapsing …) or a silent symptom (12 “monitored” servers instead of 8, a job that “Completed” with errors), place it in one of the four layers and name the first command to run.
  • Explain the mechanisms behind the 50 issues: format records vs objects, wildcard paths, argument-mode string expansion, pipeline unrolling, left-operand type coercion, regex operators, non-terminating vs terminating errors, preference-variable scoping, runspace and serialization boundaries, module session state and the PSModulePath.
  • Reproduce 45 of the 50 issues locally in ~/pslab/lab9 with snippets of a few lines; outputs in this lesson come from real runs on PowerShell 7.6.10 / .NET 10.0.15 on Windows 11 (plus Windows PowerShell 5.1.26100 for the encoding issue).
  • Fix each issue and add a prevention: a coding rule, a PSScriptAnalyzer rule, a Pester test or a CI setting.
  • Answer 50 interview questions for Senior Cloud / DevOps / Platform engineer roles in the pattern “30-second answer → mechanism → code → production story”, handle typical follow-ups and avoid the red flags interviewers listen for.
  • Review short scripts under time pressure in the order destructive → silent failure → security → concurrency → maintainability (code-review questions Q40, Q41, Q42, Q45, Q47, Q49).
  • Use the mock interview (random questions, 2-minute timer, self-rating stored in your browser) to measure mastery per module.
  • Use the triage tree (Module 4) for the most common real ticket: “the PowerShell job in CI / Task Scheduler failed (or silently did nothing)”.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab/lab9)
0Before ClassInstructions and failure labHow entries are structured; ~/pslab/lab9, helper lab9.ps1 (clean-process runner, byte viewer, sandbox), safety rules, local mock APISelf-check checklistCreate lab9.ps1, dot-source it
100–08A · Pipeline, objects and parsingIssues 1–12: Format-* mid-pipeline, brackets in -Path, "$obj.Prop", platform aliases, -Command exit codes, profile side effects, CSV “booleans”, array on the left of -eq, single-item unrolling, JSON depth, missing properties, string sortingPipeline fault tracerFormat vs Select · LiteralPath · unrolling
208–16A · Language, data and textIssues 13–25: left-operand coercion, banker's rounding, -contains vs substring, stale $Matches, regex -replace/-split, hashtable order, +=, output pollution, culture in dates and numbers, read/write the same file, multi-line matchingOperator evaluatorCoercion · regex · culture · same-file rewrite
316–24A · Errors, remoting and concurrencyIssues 26–38: non-terminating errors, leaking $ErrorActionPreference, native exit codes, deserialized objects, $using:, double hop, -Parallel functions, shared-state races, job output, ThrottleLimit, Start-Job cost, TrustedHosts, timeoutsError and runspace flowtry/catch · runspaces · races · timeouts
424–30A · Modules, cloud, CI and securityIssues 39–50: in-box Pester 3.4, edition and module paths, FunctionsToExport, PSModulePath on CI, Az context, secrets in transcripts, execution-policy myths, BOM/encoding, CRLF, REST error bodies, retries without backoff, -WhatIf not propagatedCI job simulator + triage treePester version · module export · mock API · WhatIf
530–37B · Engine and fundamentalsInterview Q1–13Answer builder + mock interview2 scenario questions
637–44B · Tool-making and dataInterview Q14–25Answer builder + mock interview2 scenario questions
744–52B · Robustness, testing and debuggingInterview Q26–38Answer builder + mock interview3 scenario questions
852–60B · Real-world scenarios and code reviewInterview Q39–50 (6 code-review questions)Answer builder + mock interview3 scenario questions
—After ClassCheat sheet · Comprehensive exercises50 “symptom → first command → fix” rows; 50 flash cards; 8 mixed failures; a full mock interviewFull mock interview (10 of 50)12-question final quiz

Knowledge Coverage Matrix

TopicM1M2M3M4M5M6M7M8Key commandsEarlier hour
Objects, formatting and pipeline binding✓·✓·✓✓·✓Get-Member, Trace-Command, Select-Object1
Parsing, quoting, wildcards, exit codes✓✓·✓✓··✓-LiteralPath, $( ), pwsh -File1
Types, operators, regex, collections✓✓··✓✓·✓-match, -replace, [ordered], List[T]2
Advanced functions and modules·✓·✓·✓✓✓[CmdletBinding()], New-ModuleManifest, Save-PSResource3, 4
Errors, streams, ShouldProcess··✓✓✓✓✓✓-ErrorAction Stop, Get-Error, -WhatIf5
Remoting, jobs, runspaces, parallelism··✓·✓·✓✓ForEach-Object -Parallel, Start-ThreadJob, Invoke-Command6
REST, cloud context, secrets··✓✓·✓✓✓Invoke-RestMethod, Set-AzContext, SecretManagement7
Testing, analysis, CI, release···✓·✓✓✓Invoke-Pester, Invoke-ScriptAnalyzer8

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Systematic teaching of each mechanism (pipeline binding, parsing modes, scopes, modules, streams, remoting, Pester)This hour starts from failures and questions; it links back instead of re-teachingHour 1 – Hour 8
OS-level failures (disk full, services, permissions, systemd, Windows event logs)Outside the scriptLinux course
Bash-side equivalents of these issues (quoting, set -e, CRLF, cron)Different shellBash Hour 8: 50 production problems + 50 interview questions
Azure / AWS platform troubleshooting beyond the PowerShell client (RBAC design, quotas, networking)Cloud platform topicsAzure and AWS courses
CI platform configuration in depthPlatform topicsGitHub, Azure DevOps courses

How to use these materials

While troubleshooting (Part A)
In a module's Overview tab, type the most distinctive word of the error (ClassId, truncated, Deserialized, not recognized, Timeout, WhatIf…) to filter; click a row to open the Issue details (symptom → reproduction → root cause → fix → prevention). No error but wrong data? Use the Animation tab or the Module 4 triage tree.
Before an interview (Part B)
Scan the Overview, then use the Mock interview tab: a random question, a 2-minute timer, answer aloud, reveal the model answer and rate yourself (answered / partial / not sure). Ratings stay in this browser. Structure every answer as conclusion → mechanism → code → production story.
Progress and narration
A quiz score of 70% or more, or “Mark this module complete”, counts toward progress (local storage). The Voice tab reads each module's key terms with the browser's Web Speech API (en-US).

Structure of the entries

Part A · 50 production issues

Symptom → minimal reproduction (a few lines, run in ~/pslab/lab9) with its output → root cause (mechanism) → fix → prevention → link to the hour that teaches the mechanism. Output labels: Actual output (7.6.10) = produced on the lab machine for this lesson; Expected output = needs remoting, a domain, a cloud tenant or Linux and was not run (listed under Known limitations). Severity: High data loss, secrets or invisible failure; Medium wrong result or failed job that is detectable; Low clear error, easy fix.

Part B · 50 interview questions

Question → 30-second answer → mechanism and code → follow-ups the interviewer is likely to ask → red flags (answers that cost you the round). Level: JuniorMidSenior. Module 8 has six code-review questions with short snippets: read them as a reviewer, not as an author.

Version notes Verified 2026-11-24. Baseline PowerShell 7.6 LTS (GA 2026-03-18, .NET 10, supported until 2028-11-14); lab machine 7.6.10 on .NET 10.0.15, Windows 11, culture en-US, ANSI code page 65001 (UTF-8 — this matters for issue #46). 7.4 LTS and 7.5 reached end of support on 2026-11-10; 7.7 is a preview. Bundled modules used here: Microsoft.PowerShell.PSResourceGet 1.2.x, PSReadLine 2.4.x, Microsoft.PowerShell.ThreadJob 2.2.0 (which replaces the old ThreadJob module). Pester: Windows still ships Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules; the PowerShell Gallery had Pester 6.2.0 on the verification date (6.0 introduced the Should-* assertion family). Windows PowerShell 5.1 (5.1.26100 on the lab machine) is used only to show edition differences.

Module 0 · Instructions and failure lab environment

Reuse ~/pslab and the Hour 1 dataset; every reproduction runs in ~/pslab/lab9 (or its disposable sandbox/), never against real systems, and every “CI-like” run uses a fresh pwsh -NoProfile -NonInteractive process
Before class ≈ 10 minRuns locally · FreeDeletes only inside ~/pslab/lab9
Prerequisites
  • PowerShell 7.6 and the dataset from Hour 1, Module 0: ~/pslab/data/ with access.log (611 lines), servers.csv (12 rows, Monitored as text), inventory.json, opskit.config.psd1 and files/ (12 odd names). Rebuild any time with ~/pslab/New-LabData.ps1.
  • Hours 1–8 are helpful but not required: every entry links to the hour that teaches the mechanism.
  • Optional: Windows PowerShell 5.1 (any Windows machine) for the edition and encoding issues; network access to the PowerShell Gallery for Save-PSResource (issue #39).

Warm-up: answer from memory (30 seconds)

1. In Hour 8 you ran OpsKit's tests in CI with pwsh -NoProfile -NonInteractive -File. What do each of the three switches protect you from?

-NoProfile: the job depends on someone's profile (issue #6). -NonInteractive: a prompt waits forever. -File: the real exit code reaches CI (with -Command an exit 3 becomes 1 — issue #5).

2. Why does try { Remove-Item $p } catch { … } often not catch anything?

Most cmdlet errors are non-terminating; catch only sees terminating errors. Add -ErrorAction Stop (issue #26, Q26).

3. What is the type of a Process object after it comes back from Invoke-Command or Start-Job?

Deserialized.System.Diagnostics.Process: a property bag without methods (issue #29).

Step 1: environment self-check

Set-Location ~/pslab/lab9      # create it first (Step 2) if it does not exist
$PSVersionTable.PSVersion.ToString(); $PSVersionTable.PSEdition
Get-Module Pester, Microsoft.PowerShell.ThreadJob, Microsoft.PowerShell.PSResourceGet -ListAvailable |
    Select-Object Name, Version
(Get-Culture).Name
Test-Path ../data/servers.csv
7.6.10
Core

Name                               Version
----                               -------
Microsoft.PowerShell.PSResourceGet 1.2.1
Microsoft.PowerShell.ThreadJob     2.2.0
Pester                             3.4.0
en-US
True

Seeing Pester 3.4.0 on Windows is normal: it is the in-box copy that ships with Windows (issue #39). Do not delete it; this lesson shows how to use a current Pester side by side without touching machine or user module folders.

Step 2: the helper script lab9.ps1

Create ~/pslab/lab9 and save this file as ~/pslab/lab9/lab9.ps1. It gives you four helpers: run code the way CI does, show invisible bytes (CR, LF, BOM), reset a disposable sandbox, and clean up everything this lesson creates.

New-Item -ItemType Directory ~/pslab/lab9 -Force | Out-Null
Set-Location ~/pslab/lab9
code ./lab9.ps1        # paste the script below and save
# usage: . ~/pslab/lab9/lab9.ps1     (dot-source into your session)
$script:L9 = Join-Path $HOME 'pslab' 'lab9'
# run a snippet the way CI / Task Scheduler would: new process, no profile, no prompts
function Invoke-L9Clean([string]$Code) {
    pwsh -NoProfile -NonInteractive -Command $Code
    "(exit=$LASTEXITCODE)"
}
# show invisible characters: CR, LF, tab, BOM
function Show-L9Bytes([string]$Path, [int]$Count = 32) {
    $b = [IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).Path) | Select-Object -First $Count
    ($b | ForEach-Object { switch ($_) { 13 {'\r'} 10 {'\n'} 9 {'\t'} default { if ($_ -lt 32 -or $_ -gt 126) { '{0:X2}' -f $_ } else { [char]$_ } } } }) -join ' '
}
# reset the disposable sandbox ~/pslab/lab9/sandbox and enter it
function Enter-L9Sandbox {
    $sb = Join-Path $script:L9 'sandbox'
    if ((Split-Path $sb -Leaf) -ne 'sandbox') { throw 'refusing' }
    if (Test-Path -LiteralPath $sb) { Remove-Item -LiteralPath $sb -Recurse -Force }
    Set-Location (New-Item -ItemType Directory -Path $sb).FullName
    "sandbox: $PWD"
}
# remove everything this lesson created (sandbox, demo modules, jobs)
function Clear-L9 {
    Get-Job | Remove-Job -Force
    Set-Location $script:L9
    'sandbox', 'modules', 'OpsDemo', 'LegacyTool', 'CleanMod', 'scratch' | ForEach-Object {
        $p = Join-Path $script:L9 $_
        if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Recurse -Force }
    }
    'lab9 cleaned'
}
. ~/pslab/lab9/lab9.ps1
Get-Command -Name *-L9* | Select-Object -ExpandProperty Name
Invoke-L9Clean 'exit 4'
Set-Content ./crlf.txt -Value 'web-01'
Show-L9Bytes ./crlf.txt
Clear-L9
Enter-L9Sandbox
Invoke-L9Clean
Show-L9Bytes
(exit=4)
w e b - 0 1 \r \n

The last line is already a production lesson: on Windows, Set-Content ends lines with CRLF; on Linux and macOS with LF (issue #47). Invoke-L9Clean is the single most useful habit of this hour — reproduce “works on my machine” bugs in a process without your profile, your variables or your imported modules.

Step 3: conventions

ConventionWhy
Run each reproduction in a fresh pwsh -NoProfile (or reset with Enter-L9Sandbox)Many issues depend on state: $Matches, $ErrorActionPreference, imported module versions, Set-StrictMode
Relative paths in snippets are relative to ~/pslab/lab9; data is read from ../dataSnippets never write to ~/pslab/data; rebuild it with New-LabData.ps1 if you break it
Issues #38, #48, #49 use a local mock API on http://localhost:8089No cloud, no internet; you control slow, failing and flaky responses
Observe → fix → run againThe fix block of each issue is meant to be pasted after the reproduction and must change the output

Step 4: the local mock API (for Modules 3 and 4)

Save as ~/pslab/lab9/mock.ps1 and start it in a second terminal (pwsh -NoProfile -File ./mock.ps1). It listens on localhost only and stops when you request /stop.

# ~/pslab/lab9/mock.ps1 - local mock API for issues 38, 48, 49 (localhost only)
# run in a second terminal: pwsh -NoProfile -File ./mock.ps1      stop: Invoke-RestMethod http://localhost:8089/stop
$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add('http://localhost:8089/')
$listener.Start()
$state = [hashtable]::Synchronized(@{ Flaky = 0; Log = (Join-Path $PSScriptRoot 'mock-hits.log') })
Set-Content -LiteralPath $state.Log -Value ''
while ($listener.IsListening) {
    $ctx = $listener.GetContext()
    if ($ctx.Request.Url.AbsolutePath -eq '/stop') { $ctx.Response.Close(); $listener.Stop(); break }
    # one thread per request, so /slow does not block the others
    $null = Start-ThreadJob -ThrottleLimit 20 -ArgumentList $ctx, $state -ScriptBlock {
        param($ctx, $state)
        $path = $ctx.Request.Url.AbsolutePath
        [System.Threading.Monitor]::Enter($state.SyncRoot)
        try {
            Add-Content -LiteralPath $state.Log -Value ('{0:HH:mm:ss.fff} {1}' -f (Get-Date), $path)
            if ($path -eq '/flaky') { $state.Flaky++ }; if ($path -eq '/reset') { $state.Flaky = 0 }
            $flaky = $state.Flaky
        } finally { [System.Threading.Monitor]::Exit($state.SyncRoot) }
        $code = 200; $body = '{"status":"ok"}'
        switch ($path) {
            '/slow'  { Start-Sleep -Seconds 5 }
            '/bad'   { $code = 400; $body = '{"error":"InvalidSku","message":"SKU Standard_X9 is not available in canadacentral"}' }
            '/flaky' { if ($flaky -le 3) { $code = 503; $body = '{"error":"busy"}' } }
        }
        $bytes = [Text.Encoding]::UTF8.GetBytes($body)
        $ctx.Response.StatusCode = $code
        $ctx.Response.ContentType = 'application/json'
        $ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length)
        $ctx.Response.Close()
    }
}
Get-Job | Remove-Job -Force

Routes: /slow answers after 5 s, /bad returns 400 with a JSON error body, /flaky returns 503 three times then 200, /reset resets the flaky counter. Every request is appended to mock-hits.log with a timestamp, so you can see retry spacing (issue #49).

Connection to the previous lessons

  • Hour 1's rules come back constantly: format right, -LiteralPath, pwsh -File, $PSScriptRoot. Hour 5's error model (terminating vs non-terminating, streams, ShouldProcess) explains Module 3 and issue #50. Hour 6 explains runspaces and serialization; Hour 8 explains Pester, PSScriptAnalyzer and CI.
  • Four triage questions for any failing job: Who (which edition and version, which account, which host: $PSVersionTable, whoami, $Host.Name) → What (the full error: Get-Error, $LASTEXITCODE, job ChildJobs.Error) → Where (pipeline, language, error handling, environment) → When (only in CI? only with one input? only in parallel?).
  • “No error but wrong result” is as common in PowerShell as in Bash. The first moves: Get-Member on the data, Invoke-L9Clean, and Set-StrictMode -Version Latest in the reproduction.

Self-check checklist

Risks and cleanup Several issues demonstrate deleting the wrong thing (#23, #50) or leaking secrets (#44). Reproductions only touch ~/pslab/lab9; the “secret” is a fake string. Never run these snippets against shared folders, production subscriptions or with an elevated account. Nothing in this lesson changes the execution policy, the PSModulePath of your user or machine, WinRM, or installs modules into a scope — Save-PSResource writes to ~/pslab/lab9/modules only. Clean up with Clear-L9, stop the mock API with Invoke-RestMethod http://localhost:8089/stop.

Module 1 · Part A: Pipeline, objects and parsing (issues 1–12)

00:00 – 08:00 · formatting objects too early, wildcard paths, string expansion, platform aliases, exit codes and profiles, text that only looks like booleans or numbers, collection semantics of comparison operators, unrolling, serialization depth
8 minobjects → format → text12 issues★★★★★
Learning objectives
  • Recognize the four “object vs text” failure patterns: an object turned into format records (#1), into a string too early (#3, #10), a string that only looks like a bool or number (#7, #12), and a collection where you expected one item or the reverse (#8, #9).
  • Know which parsing rules bite in production: wildcards in -Path (#2), argument-mode string expansion (#3), aliases that differ per platform (#4).
  • Know the process-boundary rules: -File vs -Command exit codes (#5) and profiles (#6).
  • Use the first diagnostic moves: Get-Member, .GetType(), -LiteralPath, Set-StrictMode -Version Latest.
Prerequisites: Module 0; Hour 1. Importance:★★★★★ (these are the bugs that pass code review because the code “looks right”)

Type a keyword from the error or symptom (for example ClassId, bracket, @{, exit code, true, truncated, sort) to filter; click a row to jump to the entry in “Issue details”.

#1 Export-Csv writes “ClassId2e4f51ef21dd47e99d3c952918aff9cd” instead of data (Format-Table in the middle of a pipeline)

Symptom: A report job produces a CSV (or JSON, or a log line) full of ClassId2e4f51ef…, pageHeaderEntry, shapeInfo. Someone “tidied up” the pipeline by adding Format-Table to choose the columns.

Reproduction
Import-Csv ../data/servers.csv | Format-Table Name, Env | Export-Csv ./ft.csv
Get-Content ./ft.csv -TotalCount 2
Import-Csv ../data/servers.csv | Select-Object Name, Env | Export-Csv ./ok.csv
Get-Content ./ok.csv -TotalCount 3
"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
"033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo",
"Name","Env"
"web-01","dev"
"api-01","dev"

Root cause: Format-Table does not output your objects; it outputs format records (FormatStartData, GroupStartData, FormatEntryData …) meant for Out-Default/Out-Host. Any command after it serializes those internal objects.

Fix
Import-Csv ../data/servers.csv | Select-Object Name, Env | Export-Csv ./report.csv   # choose columns with Select-Object
$rows | Format-Table Name, Env                                                         # format only for the screen, last
Prevention
  • Rule: Format-* and Out-Host only at the very end, and never inside a function that returns data.
  • Code review grep: Format-(Table|List|Wide).*\| followed by anything but Out-String/Out-Host.
  • A Pester test that imports the generated CSV and checks the header.

See Hour 1 Module 4: objects and the formatting system.

#2 Get-Content: An object at the specified path … [draft] notes.md does not exist (square brackets are wildcards in -Path)

Symptom: A file clearly exists (you can see it in Explorer), but Get-Content, Copy-Item or Test-Path say it does not — or worse, Remove-Item silently matches a different file. Typical names: report[2026].xlsx, [draft] notes.md, SharePoint exports.

Reproduction
Get-Content '../data/files/[draft] notes.md'
Test-Path '../data/files/[draft] notes.md'
Test-Path -LiteralPath '../data/files/[draft] notes.md'
Get-Content -LiteralPath '../data/files/[draft] notes.md'
Get-Content: An object at the specified path ../data/files/[draft] notes.md does not exist, or has been filtered by the -Include or -Exclude parameter.
False
True
file #3

Root cause: -Path (the positional parameter of most provider cmdlets) interprets *, ? and [ ] as wildcards. [draft] is a character class meaning “one of d, r, a, f, t”, so the pattern matches d notes.md, not the real file. Test-Path returns False without an error — a silent failure in an if.

Fix
Get-Content -LiteralPath $file
Get-ChildItem ../data/files -File | Get-Content      # piped FileInfo binds to -LiteralPath (PSPath alias)
[WildcardPattern]::Escape('[draft] notes.md')        # when an API only offers -Path
Prevention
  • In scripts, use -LiteralPath whenever the path comes from data (files, CSV, user input).
  • Keep “odd names” (~/pslab/data/files) in your test fixtures.

See Hour 1 Module 7: wildcards and -LiteralPath.

#3 Log says “Deploying to @{Name=web-01; Env=dev; …}.Name” (property access inside double quotes)

Symptom: Messages, file names or API payloads contain @{Name=…}.Name or System.Object[].Count. Worse when the string is a path: a folder named @{Name=web-01; …}.Name appears.

Reproduction
$s = Import-Csv ../data/servers.csv | Select-Object -First 1
"Deploying to $s.Name in $s.Env"
"Deploying to $($s.Name) in $($s.Env)"
Deploying to @{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}.Name in @{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}.Env
Deploying to web-01 in dev

Root cause: In an expandable string only the simple variable $s is expanded; .Name is literal text. The object is converted with its ToString(), which for a PSCustomObject is the @{…} hashtable-like text.

Fix
"Deploying to $($s.Name) in $($s.Env)"
'Deploying to {0} in {1}' -f $s.Name, $s.Env
Prevention
  • Use $( ) for anything beyond a plain variable, or the -f operator for templates.
  • Search code for "[^"]*\$\w+\.\w+ during review.

See Hour 1 Module 7: subexpressions.

#4 Works on Windows, on Linux “sort” / “ls” / “curl” return text or different results (aliases differ per platform)

Symptom: A script developed on Windows runs on a Linux runner: ls | Where-Object Length -gt 1KB returns nothing, sort sorts lines as text, cat behaves differently. On Windows itself, curl in PowerShell 7 is not Invoke-WebRequest any more.

Reproduction (Windows)
Get-Alias ls, cat, sort, curl, wget -ErrorAction SilentlyContinue |
    Select-Object Name, Definition
(Get-Command curl).CommandType
(Get-Command curl).Source
Name Definition
---- ----------
ls   Get-ChildItem
cat  Get-Content
sort Sort-Object
Application
C:\Program Files\Git\mingw64\bin\curl.exe
Name Definition
---- ----------
(nothing: ls, cat, sort run /usr/bin/ls, /usr/bin/cat, /usr/bin/sort and return text)

Root cause: PowerShell defines Unix-named convenience aliases (ls, cat, sort, cp, rm …) only on Windows; on Linux and macOS the native programs win. curl/wget aliases were removed from PowerShell 6+ on all platforms, so curl runs whichever curl executable is first on PATH. The output is text, not objects.

Fix and prevention
  • Use full cmdlet names in scripts (Get-ChildItem, Sort-Object, Invoke-RestMethod).
  • Enable PSScriptAnalyzer rule PSAvoidUsingCmdletAliases in CI (Hour 8).
  • Run the test suite on a Linux runner too (CI matrix).

See Hour 1 Module 2: command precedence.

#5 CI step always reports exit code 1, never the script's own code (pwsh -Command flattens exit codes)

Symptom: A deploy script returns 3 for “drift detected, needs approval”, but the pipeline only ever sees 0 or 1, so the approval branch never runs.

Reproduction
Set-Content ./exit3.ps1 -Value 'exit 3'
pwsh -NoProfile -File ./exit3.ps1;    "-File    : $LASTEXITCODE"
pwsh -NoProfile -Command ./exit3.ps1; "-Command : $LASTEXITCODE"
pwsh -NoProfile -Command './exit3.ps1; exit $LASTEXITCODE'; "fixed    : $LASTEXITCODE"
-File    : 3
-Command : 1
fixed    : 3

Root cause: With -Command, the process exit code is derived from $? of the last statement (0 or 1), not from the script's exit N. -File passes the script's exit code through.

Fix
pwsh -NoProfile -NonInteractive -File ./deploy.ps1 -Environment prod
# if you must use -Command:
pwsh -NoProfile -Command './deploy.ps1 -Environment prod; exit $LASTEXITCODE'
Prevention
  • A standard wrapper line for all schedulers and CI: pwsh -NoProfile -NonInteractive -File.
  • A CI smoke test that runs a script which exits 3 and asserts the step's exit code.

See Hour 1 Module 8.

#6 Works interactively, fails in CI: “The term 'Show-Greeting' is not recognized” (the script depended on a profile)

Symptom: A function, alias, module path, proxy setting or $PSDefaultParameterValues entry exists on the author's machine and nowhere else. Or the reverse: a scheduled task is slow and prints strange output because the service account's profile runs (profiles load for -File and -Command too, unless -NoProfile).

Reproduction: what a profile-free process sees
# what a profile-free run (CI, Task Scheduler with -NoProfile, another account) sees
pwsh -NoProfile -Command 'Get-Command Show-Greeting -ErrorAction SilentlyContinue; "found: $?"; $PROFILE.CurrentUserAllHosts'
found: False
C:\Users\labadmin\Documents\PowerShell\profile.ps1

Root cause: The interactive session had four profile scripts dot-sourced into it (Hour 1 Module 1). Code tested only there silently depends on them. Without -NoProfile, automation also inherits whatever the running account's profile does (prompt changes, Set-Location, slow module imports, even $ErrorActionPreference).

Fix
# in the script: declare every dependency explicitly
#Requires -Modules @{ ModuleName = 'OpsKit'; ModuleVersion = '1.0.0' }
Import-Module OpsKit -ErrorAction Stop
# in the scheduler / CI step:
pwsh -NoProfile -NonInteractive -File ./job.ps1
Prevention
  • Reproduce every bug report with Invoke-L9Clean first.
  • Keep profiles for interactive convenience only (prompt, PSReadLine); never put code that scripts need in them.

See Hour 1 Module 1: profiles and startup.

#7 Where-Object { $_.Monitored } returns all 12 servers, including the 4 with Monitored = false (CSV values are strings)

Symptom: Alerting is configured for servers that should be excluded; a cleanup job acts on rows marked false, 0 or no.

Reproduction
$servers = Import-Csv ../data/servers.csv
@($servers | Where-Object { $_.Monitored }).Count
@($servers | Where-Object { [bool]$_.Monitored }).Count
@($servers | Where-Object { $_.Monitored -eq 'true' }).Count
@($servers | Where-Object { [bool]::Parse($_.Monitored) }).Count
[bool]'false'
12
12
8
8
True

Root cause: Import-Csv produces strings. In PowerShell, any non-empty string is $true, including 'false' and '0'. [bool]'false' is a conversion of a string to bool, not a parse.

Fix
$servers | Where-Object Monitored -eq 'true'                      # compare text explicitly
$servers | Select-Object *, @{ n = 'IsMonitored'; e = { [bool]::Parse($_.Monitored) } }   # convert once, fail on bad data
Prevention
  • Convert CSV columns to real types at the boundary (one Select-Object or a class), then work with typed objects.
  • Prefer JSON (inventory.json keeps real booleans) for machine-to-machine data.

See Hour 1 Module 6; Hour 2: types.

#8 if ($ids -eq $null) says “no null” although the array contains $null (comparison operators filter collections)

Symptom: Validation code says the list is fine when it is not; if ($roles -eq 'db') works in tests with one item and fails with several; if ($flags -ne 0) is false although a flag is set to 1 in a different test.

Reproduction
$ids = @(3, $null, 7)
if ($ids -eq $null) { 'has null' } else { 'no null (wrong!)' }
if ($null -eq $ids) { 'array is null' } else { 'array is not null' }
$roles = 'web', 'api'
$roles -eq 'api'
if ($roles -eq 'db') { 'db role' } else { 'no db role' }
$flags = @(0, 0)
if ($flags -ne 0) { 'some flag set' } else { 'no flag set' }
no null (wrong!)
array is not null
api
no db role
no flag set

Root cause: When the left operand is a collection, -eq, -ne, -match, -like act as filters and return the matching elements. @(3,$null,7) -eq $null returns @($null), and a one-element array is truthy only if that element is: $null → false. @(0,0) -ne 0 returns an empty array → false — correct here, but for the wrong reason.

Fix
if ($null -eq $value) { … }             # $null always on the left
if ($ids -contains $null) { … }         # membership: -contains / -in
if (@($flags -ne 0).Count -gt 0) { … }  # explicit count when you filter
Prevention
  • PSScriptAnalyzer rule PSPossibleIncorrectComparisonWithNull flags $x -eq $null.
  • Use -contains/-in for membership; never rely on the truthiness of a filtered array.

See Hour 2: operators; interview Q9.

#9 $one[0] returns “b” instead of “bastion-01”; JSON has a string instead of an array (single results are unrolled)

Symptom: Code works when a query returns several items but breaks when it returns exactly one: indexing returns a character, .Count logic or foreach over characters appears in older code, and an API receives "bastion-01" where its schema requires ["bastion-01"].

Reproduction
function Get-Name([string]$Pattern) {
    Import-Csv ../data/servers.csv | Where-Object Name -like $Pattern | ForEach-Object Name
}
$many = Get-Name 'web-*'
$one  = Get-Name 'bastion-*'
$many[0]; $one[0]
$one.GetType().Name
@(Get-Name 'bastion-*')[0]
Get-Name 'bastion-*' | ConvertTo-Json -Compress
ConvertTo-Json -InputObject @(Get-Name 'bastion-*') -Compress
web-01
b
String
bastion-01
"bastion-01"
["bastion-01"]

Root cause: The pipeline unrolls collections and a function's output is collected by the caller: zero items → $null, one item → that item (here a String), several → Object[]. Indexing a string returns a char. Piping to ConvertTo-Json serializes each item separately.

Fix
$names = @(Get-Name 'bastion-*')                         # caller: always an array
ConvertTo-Json -InputObject @($names) -Depth 5            # JSON array guaranteed
return , $list                                            # function: emit the collection as ONE object (use sparingly)
Prevention
  • Wrap every “list” result in @( ) at the call site; type parameters as [string[]].
  • Write tests for the 0, 1 and many cases (Pester -ForEach).

See Hour 2: arrays; interview Q10.

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

Symptom: A config or API payload written with ConvertTo-Json contains "System.Collections.Hashtable" or "@{…}" strings for nested parts. In scheduled jobs nobody sees the warning; the next run reads a broken config.

Reproduction
$cfg = Import-PowerShellDataFile ../data/opskit.config.psd1
$json = @{ Opskit = $cfg } | ConvertTo-Json -Compress
$json.Substring(0, 90)
$full = @{ Opskit = $cfg } | ConvertTo-Json -Compress -Depth 10
($full | ConvertFrom-Json).Opskit.Environments.prod.HealthUrl
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"Opskit":{"LogLevel":"Information","Inventory":"~/pslab/data/servers.csv","DefaultEnv":"d
https://shop.example.com/healthz

Root cause: ConvertTo-Json has -Depth 2 by default. Deeper levels are converted with ToString(). PowerShell 7 at least writes a warning (Windows PowerShell 5.1 truncated silently); the warning stream is often not captured in automation.

Fix
$obj | ConvertTo-Json -Depth 10            # explicit depth everywhere (max 100)
$PSDefaultParameterValues['ConvertTo-Json:Depth'] = 10   # per-script default, not in a profile
Prevention
  • Always pass -Depth; round-trip test: ConvertTo-Json | ConvertFrom-Json and compare a deep value (as in the reproduction).
  • Treat warnings as failures in CI: -WarningAction Stop on serialization steps.

See Hour 2: JSON.

#11 Where-Object Enviroment -eq 'prod' returns nothing and no error (misspelled property)

Symptom: A report is empty, a cleanup does nothing, a “no prod servers affected” check passes. The property name has a typo or the data source renamed a column (Env → Environment).

Reproduction
$servers = Import-Csv ../data/servers.csv
@($servers | Where-Object Enviroment -eq 'prod').Count     # typo: Enviroment
@($servers | Where-Object { $_.Enviroment -eq 'prod' }).Count
Set-StrictMode -Version Latest
@($servers | Where-Object { $_.Enviroment -eq 'prod' }).Count
0
0
PropertyNotFoundException: 
Line |
   5 |  @($servers | Where-Object { $_.Enviroment -eq 'prod' }).Count
     |                              ~~~~~~~~~~~~~~~~~~~~~~~~
     | The property 'Enviroment' cannot be found on this object. Verify that the property exists.
… (the same error 11 more times, once per CSV row)
0

Root cause: Accessing a missing property returns $null silently. The simplified syntax Where-Object Prop -eq x is not affected by strict mode at all (first count); the script-block form throws only under Set-StrictMode -Version Latest (as a non-terminating error per object, so the count is still printed).

Fix
$required = 'Name', 'Env', 'IP'
$missing  = $required | Where-Object { $_ -notin $servers[0].PSObject.Properties.Name }
if ($missing) { throw "servers.csv is missing columns: $($missing -join ', ')" }
Prevention
  • Validate the schema of external data at the boundary (columns, types) and fail fast.
  • Set-StrictMode -Version Latest in scripts and module files; tests that assert a non-empty result for known data.

See Hour 5; interview Q37 (StrictMode).

#12 “Top connections” report puts 9 above 100 (Sort-Object compares strings)

Symptom: Sorting by a numeric-looking column from CSV, logs or -split output gives 9 > 100 > 10; thresholds like -gt 100 also misbehave (see #13).

Reproduction
$rows = 'web-01,10', 'web-02,9', 'api-01,100' | ConvertFrom-Csv -Header Name, Conns
($rows | Sort-Object Conns -Descending).Name -join ' > '
($rows | Sort-Object { [int]$_.Conns } -Descending).Name -join ' > '
($rows | Measure-Object Conns -Maximum).Maximum
web-02 > api-01 > web-01
api-01 > web-01 > web-02
100

Root cause: The property is a String, so Sort-Object uses culture-aware string comparison. Measure-Object converts to numbers, which is why the maximum is right while the sort is wrong — a confusing mix.

Fix
$rows | Sort-Object { [int]$_.Conns } -Descending
$rows = $rows | Select-Object Name, @{ n = 'Conns'; e = { [int]$_.Conns } }   # convert once
Prevention
  • Convert at the boundary (as in #7). Check types with Get-Member before sorting or comparing.

See Hour 1 Module 6.

Where object data turns into something else

SourceImport-Csv · Get-Item · REST Path / name parsing#2 wildcards · #4 aliases Objects in the pipe#7 #12 strings · #8 #9 arrays Conversion#3 ToString · #10 depth · #1 format Sinkfile · API · exit code #5 First diagnostic moves $x | Get-Member · $x.GetType().FullName @($x).Count · $x | ConvertTo-Json -Depth 5 Test-Path -LiteralPath · Get-Command name -All Invoke-L9Clean '…' (no profile, new process) Set-StrictMode -Version Latest Rules that prevent all 12 Select-Object to shape, Format-* only last (#1) -LiteralPath for data paths, full cmdlet names (#2 #4) "$($o.Prop)" · ConvertTo-Json -Depth (#3 #10) Type at the boundary; $null on the left; @() (#7–#9 #11 #12) pwsh -NoProfile -NonInteractive -File (#5 #6)
Figure 1-1: each issue sits at one stage; most of them are an object silently becoming text, or text pretending to be an object
What the caller receives from a function or pipeline (#9) 0 items$nullforeach runs 0 times · .Count = 0ConvertTo-Json → (nothing) 1 itemthe item itself (String, PSCustomObject…)$x[0] on a String → first charConvertTo-Json → "value" (no [ ]) 2+ itemsObject[]$x[0] → first item@( ) makes all three cases look like this
Figure 1-2: wrap list results in @( ) at the call site

Pipeline fault tracer

Choose a symptom and step through the stages: green = data still correct, yellow = data changed shape, red = the stage where the bug is created. The console lines are real 7.6.10 output from the reproductions.

Ready.

Goal: reproduce, fix and guard four issues of this module. Environment: pwsh 7.6, ~/pslab/lab9, data in ~/pslab/data. Cost: none.

Lab 1-A · format vs select (#1). Run the reproduction of #1, then write a guard: a function that refuses format records.
function Assert-NotFormatted { process {
    if ($_.GetType().FullName -like 'Microsoft.PowerShell.Commands.Internal.Format.*') {
        throw 'Format-* output reached a data sink; use Select-Object instead.' }
    $_ } }
Import-Csv ../data/servers.csv | Format-Table Name | Assert-NotFormatted | Export-Csv ./x.csv

Verified on 7.6.10: the pipeline stops with Exception: … Format-* output reached a data sink; use Select-Object instead. Note that x.csv still exists as an empty file: Export-Csv creates its file in its begin block, before any object arrives — write to a temp file and rename on success when partial output matters.

Lab 1-B · odd names (#2). Count how many of the 12 files in ../data/files can be read by name through -Path and through -LiteralPath:
$names = Get-ChildItem ../data/files -File -Recurse -Force | ForEach-Object FullName
@($names | Where-Object { Test-Path $_ }).Count
@($names | Where-Object { Test-Path -LiteralPath $_ }).Count

Verified on 7.6.10: 11 with -Path, 12 with -LiteralPath; the one failure is [draft] notes.md. tick`mark.txt passes on 7.6 because 7.6 fixed how a lone backtick is treated in wildcard patterns; do not rely on that on older versions.

Lab 1-C · 0 / 1 / many (#9). Call Get-Name from the reproduction with 'nope*', 'bastion-*' and 'web-*'; print .GetType().Name and @( ).Count for each. Then change the call sites to @(Get-Name …) and confirm the JSON is always an array.
Lab 1-D · exit codes (#5). Add a Pester test to OpsKit (Hour 8) that starts pwsh -NoProfile -File on a script that exits 3 and asserts $LASTEXITCODE -eq 3.
Cleanup: Remove-Item ./ft.csv, ./ok.csv, ./x.csv, ./exit3.ps1 -ErrorAction Ignore
Scenario questions
A report script works, but someone added | Format-Table -AutoSize inside the function Get-OpsReport “to make it look nice”. Two other scripts consume its output. What breaks and how do you fix it without losing the nice view?

Consumers now receive format records (#1): CSV exports show ClassId…, property access returns nothing. Remove formatting from the function; return objects. For the nice view, add a format definition (.ps1xml with a TableControl, Hour 3/4) or a type name with DefaultDisplayPropertySet, so the default view is pretty while the data stays intact.

A CI job filters Import-Csv hosts.csv | Where-Object { $_.Enabled } and patches every host, including disabled ones. List two fixes and one test.

Compare text explicitly (Enabled -eq 'true') or convert with [bool]::Parse at import (#7). Test: a fixture with false, False, 0 and empty values that asserts those hosts are excluded (and that an invalid value fails loudly).

Verified teaching videos

▶
PowerShell Quiz & Quirks — PowerShell Conference Europe
English · conference talk on surprising behaviour (#3, #8, #9, #13)
▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · objects, pipeline, formatting (#1, #7)

No verified video focuses on wildcard paths, unrolling or ConvertTo-Json depth; use the reproductions and the storyboard below.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: a CSV opens full of ClassId2e4f… ; rewind, Format-Table turns into Select-Object.
Narration: Format cmdlets produce instructions for the screen, not data.
Shot 2 · 30–60s
Visual: [bool]'false' prints True; 12 servers light up instead of 8.
Narration: CSV gives you strings; convert at the boundary.
Shot 3 · 60–90s
Visual: three boxes 0 / 1 / many items; @( ) wraps them into one shape.
Narration: one result is not an array unless you ask for one.
or score ≥ 70% on the Quiz

Module 2 · Part A: Language, data and text (issues 13–25)

08:00 – 16:00 · the left operand decides the type, rounding to even, membership vs substring, automatic variables that keep old values, regex-based operators, unordered hashtables, array growth, accidental function output, culture in dates and numbers, rewriting a file you are still reading, line-based matching
8 mintypes → operators → text13 issues★★★★☆
Learning objectives
  • Predict results of mixed-type expressions: the left operand's type wins (#13), [int] casts round half to even (#14).
  • Choose the right operator: -contains/-in for membership, -like/-match for text (#15); remember that -match, -replace and -split are regex (#16–#18).
  • Avoid hidden output and hidden cost: everything not captured is returned (#21); += copies the array (#20); @{} has no order (#19).
  • Make text handling culture-safe and file-safe (#22–#25).
Prerequisites: Module 1; Hour 2: Language Essentials. Importance:★★★★☆

Filter by a keyword (string, round, contains, $Matches, regex, order, +=, culture, being used, multiline) and click a row.

#13 '10' -lt 9 is True; a port check “$port -gt 100” passes for port 21 (the left operand decides the comparison type)

Symptom: Threshold checks are wrong only for some inputs; string concatenation appears where you expected addition.

Reproduction
'10' -lt 9          # left operand is a string -> string comparison
10 -lt '9'          # left operand is a number -> numeric comparison
'1' + 1
1 + '1'
$port = (Import-Csv ../data/servers.csv)[0].IP.Split('.')[-1]   # "21", a string
$port -gt 100
[int]$port -gt 100
True
False
11
2
True
False

Root cause: PowerShell converts the right operand to the type of the left one. '10' -lt 9 becomes the string comparison '10' -lt '9' (“1” sorts before “9”); '21' -gt 100 compares '21' with '100'. + follows the same rule (concatenation vs addition).

Fix and prevention
[int]$port -gt 100                       # cast the data, not the literal
[int]$threshold = $config.Threshold      # typed variables keep the type on later assignments
param([ValidateRange(1, 65535)][int]$Port)   # typed parameters convert and validate once

See Hour 2: types and operators; interview Q9.

#14 [int]2.5 is 2 but [int]3.5 is 4; capacity maths is off by one (banker's rounding)

Symptom: A script computing “number of nodes = load / capacity” or batch sizes produces inconsistent results; [int] is used as “truncate”.

Reproduction
[int]2.5; [int]3.5; [int]-2.5
[math]::Round(2.5)
[math]::Round(2.5, [MidpointRounding]::AwayFromZero)
[math]::Floor(7 / 2)
7 / 2
[int](7 / 2)
2
4
-2
2
3
3
3.5
4

Root cause: Casting to [int] rounds, and .NET's default midpoint rule is to even (MidpointRounding.ToEven). / always produces a double when the result is not whole (7 / 2 = 3.5), unlike integer division in C# or Bash's $(( )).

Fix and prevention
[math]::Floor($a / $b); [math]::Ceiling($load / $capacity)      # say what you mean
[math]::Round($x, 0, [MidpointRounding]::AwayFromZero)          # “school” rounding
[math]::DivRem(7, 2)                                             # quotient and remainder

Related trap found while writing this lesson: [math]::Min(30, 0.5) returns 0 because PowerShell picks the Min(int, int) overload and rounds 0.5 to even — see issue #49.

#15 'web,api' -contains 'api' is False (‑contains is collection membership, not substring)

Symptom: Role or tag checks never match on multi-value fields such as Role = "web,api" (row edge-01), or match case-insensitively when you needed exact case.

Reproduction
'web,api' -contains 'api'
'api' -in 'web,api'
'web', 'api' -contains 'api'
'web,api' -like '*api*'
'web,api' -split ',' -contains 'api'
'PROD' -eq 'prod'; 'PROD' -ceq 'prod'
False
False
True
True
True
True
False

Root cause: -contains/-in test whether a collection has an element equal to the value; a single string is a one-element collection. All comparison operators are case-insensitive by default; the c prefix (-ceq, -cmatch) makes them case-sensitive.

Fix and prevention
($s.Role -split ',') -contains 'api'     # split into a collection first
$s.Role -like '*api*'                    # or a substring/wildcard test (careful: matches "rapid")
$s.Role -split ',' | ForEach-Object Trim # normalize when you import

See Hour 2.

#16 Parser reports values from the previous line ($Matches is not cleared when -match fails)

Symptom: A log parser emits a record for a line that did not match, with the fields of the previous record — duplicate alerts, wrong IPs in incident tickets.

Reproduction
$lines = Get-Content ../data/access.log
if ($lines[0] -match '"(\w+) (\S+)') { "first:  $($Matches[1]) $($Matches[2])" }
$null = $lines[1] -match 'NO-SUCH-TEXT'
"second: $($Matches[1]) $($Matches[2])     <- stale, from line 1"
$hit = $lines[0..2] -match 'healthz'
$hit.GetType().Name; $hit.Count
first:  GET /healthz
second: GET /healthz     <- stale, from line 1
Object[]
2

Root cause: $Matches is set only when a scalar -match succeeds; a failed match leaves it unchanged. With an array on the left, -match filters and does not set $Matches at all (it returns the matching lines, here two).

Fix and prevention
if ($line -match $pattern) { $Matches.ip }          # use $Matches only inside the if
$m = [regex]::Match($line, $pattern); if ($m.Success) { $m.Groups['ip'].Value }
Select-String -Path ../data/access.log -Pattern '^(?<ip>\S+)' | ForEach-Object { $_.Matches[0].Groups['ip'].Value }
#17 '10.30.1.41' -replace '.', '-' returns “----------”; a password with $$ loses a dollar sign (‑replace is regex on both sides)

Symptom: Renamed files, IPs or config values come out garbled; a templated secret is written with one $ missing and the service cannot log in.

Reproduction
'10.30.1.41' -replace '.', '-'
'10.30.1.41' -replace '\.', '-'
'10.30.1.41' -replace [regex]::Escape('.'), '-'
'10.30.1.41'.Replace('.', '-')
'password=CHANGEME' -replace 'CHANGEME', 'p@$$w0rd'
'password=CHANGEME'.Replace('CHANGEME', 'p@$$w0rd')
----------
10-30-1-41
10-30-1-41
10-30-1-41
password=p@$w0rd
password=p@$$w0rd

Root cause: The pattern of -replace is a regular expression (. = any character). The replacement string is a .NET substitution string: $1, $&, ${name} are group references and $$ means one literal $. The string method .Replace() is literal on both sides (and case-sensitive).

Fix and prevention
$text -replace [regex]::Escape($find), $value.Replace('$', '$$')   # literal find and replace with -replace
$text.Replace($find, $value)                                          # or simply the literal method
$text -replace $find, { $value }                                      # 6.1+: script-block replacement is not interpreted

Also note single quotes around patterns: in double quotes PowerShell itself would expand $1 as a variable first.

#18 'web|api' -split '|' returns 9 pieces (‑split is regex, empty fields are kept)

Symptom: Parsing pipe-separated or dot-separated data produces single characters and empty strings; CSV-like lines with empty fields shift columns.

Reproduction
('web|api' -split '|').Count
'web|api' -split '\|'
'web|api' -split '|', 0, 'SimpleMatch'
'a,b,,c' -split ','  | ForEach-Object { "[$_]" }
'k=v=w' -split '=', 2
9
web
api
web
api
[a]
[b]
[]
[c]
k
v=w

Root cause: | is regex alternation between two empty patterns, which matches between every character. -split keeps empty elements (here []); the optional max-count (, 2) limits the number of pieces.

Fix and prevention
$line -split '\|'                          # escape
$line -split '|', 0, 'SimpleMatch'         # literal
$line.Split('|')                           # .NET literal split
Import-Csv -Delimiter '|' -Path ./data.psv # real delimited data: use the CSV parser (quotes, embedded delimiters)
#19 JSON / CSV columns come out in a random order; diffs show changes on every run (@{} is unordered)

Symptom: Generated config files change on every deployment although no value changed; a downstream system that reads columns by position breaks.

Reproduction
$h = @{ Name = 'web-01'; Env = 'prod'; IP = '10.30.1.41'; Role = 'web' }
($h | ConvertTo-Json -Compress)
$o = [ordered]@{ Name = 'web-01'; Env = 'prod'; IP = '10.30.1.41'; Role = 'web' }
($o | ConvertTo-Json -Compress)
[pscustomobject]$o | ConvertTo-Csv | Select-Object -First 1
{"Role":"web","IP":"10.30.1.41","Env":"prod","Name":"web-01"}
{"Name":"web-01","Env":"prod","IP":"10.30.1.41","Role":"web"}
"Name","Env","IP","Role"

Root cause: @{} is a Hashtable: enumeration order depends on hash codes, not insertion. [ordered]@{} is an OrderedDictionary; [pscustomobject]@{…} written as a literal also keeps the written order.

Fix and prevention
[pscustomobject]@{ Name = $n; Env = $e; IP = $ip }      # literal cast keeps order
[ordered]@{ Name = $n; Env = $e }                         # ordered dictionary
$obj | Select-Object Name, Env, IP | Export-Csv …          # or state the column order explicitly
#20 A report over 20,000 rows takes seconds (or minutes) in a loop with $array += $item

Symptom: A script is fast with test data and slow in production; CPU is high and memory churns. The code builds the result with $result += ….

Reproduction
$n = 20000
$t1 = Measure-Command { $a = @(); foreach ($i in 1..$n) { $a += $i } }
$t2 = Measure-Command { $l = [System.Collections.Generic.List[int]]::new(); foreach ($i in 1..$n) { $l.Add($i) } }
$t3 = Measure-Command { $c = foreach ($i in 1..$n) { $i } }
'{0,-22} {1,8:N0} ms' -f 'array +=', $t1.TotalMilliseconds
'{0,-22} {1,8:N0} ms' -f 'List[int].Add()', $t2.TotalMilliseconds
'{0,-22} {1,8:N0} ms' -f 'collect loop output', $t3.TotalMilliseconds
array +=                  1,321 ms
List[int].Add()             421 ms
collect loop output          36 ms

Root cause: .NET arrays have a fixed size; += allocates a new array and copies all elements on every addition — quadratic work. PowerShell 7.5 made += cheaper, but it still copies. Letting the loop emit values and assigning the whole loop to a variable is both the simplest and the fastest pattern.

Fix and prevention
$rows = foreach ($s in $servers) { [pscustomobject]@{ Name = $s.Name; Env = $s.Env } }
$list = [System.Collections.Generic.List[object]]::new(); $list.Add($x)   # when you must add conditionally in many places

Enforce this one in code review: search for += on a variable initialised with @() inside loops. See interview Q22.

#21 Function returns “0,1,2,3,4,5,web-01,…” — 12 items instead of 6 (uncaptured output becomes return value)

Symptom: A function returns extra values: indexes from ArrayList.Add(), True from HashSet.Add(), DirectoryInfo from New-Item, text from a native command. Callers get the wrong count or the wrong type.

Reproduction
function Get-ProdNames {
    $list = [System.Collections.ArrayList]::new()
    foreach ($s in Import-Csv ../data/servers.csv) {
        if ($s.Env -eq 'prod') { $list.Add($s.Name) }
    }
    return $list
}
$r = Get-ProdNames
$r.Count
$r -join ','
12
0,1,2,3,4,5,web-01,web-02,api-01,edge-01,db-01,bastion-01

Root cause: In PowerShell, every value a statement produces and nobody captures goes to the success stream — that is the function's output. return $list only adds the list at the end; it does not discard what was already emitted. ArrayList.Add returns the new index.

Fix and prevention
$null = $list.Add($s.Name)               # discard explicitly (fastest)
[void]$list.Add($s.Name)
New-Item -ItemType Directory $p | Out-Null
$list = [System.Collections.Generic.List[string]]::new()   # List[T].Add returns void

Test the output type and count of every public function (Pester: @(Get-ProdNames).Count | Should-Be 6). Interview Q18.

#22 Maintenance window scheduled on 3 April instead of 4 March (date parsing depends on how you parse)

Symptom: The same script parses dates differently on a build agent in another region, or differently in two places of the same script.

Reproduction (culture set to en-GB inside the process)
[cultureinfo]::CurrentCulture = 'en-GB'
([datetime]'03/04/2026').ToString('yyyy-MM-dd')          # cast: invariant culture
(Get-Date -Date '03/04/2026').ToString('yyyy-MM-dd')       # cmdlet: current culture
[datetime]::ParseExact('03/04/2026', 'dd/MM/yyyy', [cultureinfo]::InvariantCulture).ToString('yyyy-MM-dd')
(Get-Date -Date '2026-11-24T10:00:01Z').ToUniversalTime().ToString('o')
2026-03-04
2026-04-03
2026-04-03
2026-11-24T10:00:01.0000000Z

Root cause: A cast ([datetime]'03/04/2026') uses the invariant culture (month first). A cmdlet parameter (Get-Date -Date) converts with the current culture (en-GB: day first). Same text, two answers. Times without an offset are also ambiguous between local and UTC.

Fix and prevention
[datetime]::ParseExact($s, 'yyyy-MM-dd', [cultureinfo]::InvariantCulture)
Get-Date -AsUTC -Format o                               # write ISO 8601 with offset
[datetimeoffset]::Parse('2026-11-24T10:00:01Z')         # keep the offset

Exchange dates only as ISO 8601 (yyyy-MM-ddTHH:mm:ssZ) and log in UTC.

#23 Set-Content: The process cannot access the file … because it is being used by another process (reading and writing the same file in one pipeline)

Symptom: An in-place “sed”-style edit fails; on other platforms or versions it can produce an empty or truncated file, which is worse.

Reproduction
Copy-Item ../data/servers.csv ./servers.csv
Get-Content ./servers.csv | ForEach-Object { $_ -replace 'canadacentral', 'canadaeast' } |
    Set-Content ./servers.csv
(Get-Item ./servers.csv).Length
Copy-Item ../data/servers.csv ./servers.csv
(Get-Content ./servers.csv) -replace 'canadacentral', 'canadaeast' | Set-Content ./servers.csv
(Get-Item ./servers.csv).Length
@(Select-String -Path ./servers.csv -Pattern 'canadaeast').Count
Set-Content: 
Line |
   3 |      Set-Content ./servers.csv
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~
     | The process cannot access the file 'C:\Users\labadmin\pslab\lab9\servers.csv' because it is being used by another process.
600
592
7

Root cause: Get-Content streams the file line by line and keeps it open while Set-Content, further down the same pipeline, tries to open it for writing. Wrapping Get-Content in parentheses reads the whole file first and closes it. Notice the size: 600 → 592 bytes although we removed 21 characters — Set-Content wrote CRLF line endings on Windows (13 extra bytes; issue #47).

Fix and prevention
$tmp = "$path.tmp"
(Get-Content -LiteralPath $path) -replace $old, $new | Set-Content -LiteralPath $tmp
Move-Item -LiteralPath $tmp -Destination $path -Force       # atomic-ish replace, original intact on failure

Always write to a temp file and rename; keep a backup for config files. Pin the line ending if consumers care (-join "`n" + Set-Content -NoNewline).

#24 [double]'1,5' is 15 and '{0:N2}' prints 1.234,50 on a German build agent (number culture)

Symptom: Prices, percentages or thresholds read from config or written to reports are off by a factor of 10 or 100 on some machines; JSON produced with string templates is invalid.

Reproduction (culture set to de-DE inside the process)
[cultureinfo]::CurrentCulture = 'de-DE'
'{0:N2}' -f 1234.5
"$(1234.5)"
[string]1234.5
(1234.5).ToString()
[double]::Parse('1,5')
[double]'1,5'
1.234,50
1234.5
1234.5
1234,5
1,5
15

Root cause: PowerShell's casts and string expansion ("$x", [string]$x, [double]'…') use the invariant culture, so [double]'1,5' treats the comma as a thousands separator → 15. .NET methods and format strings (.ToString(), -f, [double]::Parse) use the current culture → 1234,5, 1,5.

Fix and prevention
[double]::Parse($s, [cultureinfo]::InvariantCulture)
$x.ToString([cultureinfo]::InvariantCulture)
$obj | ConvertTo-Json                 # let the serializer format numbers

Run CI once with a non-English culture ([cultureinfo]::CurrentCulture = 'de-DE' at the top of a test run).

#25 Select-String finds nothing for a two-line pattern; '(?m)^status: ok$' fails on a file written on Windows (line-based matching and \r)

Symptom: A health-check parser never detects “degraded” blocks that span lines; a multi-line regex that works in an online tester fails on real files.

Reproduction
$text = "server: web-01`nstatus: degraded`nserver: api-01`nstatus: ok"
Set-Content ./status.txt -Value $text
@(Select-String -Path ./status.txt -Pattern 'web-01\s+status: degraded').Count
$raw = Get-Content ./status.txt -Raw
$raw -match 'web-01\s+status: degraded'
$raw -match '^status: ok$'
$raw -match '(?m)^status: ok$'
$raw -match '(?m)^status: ok\r?$'
0
True
False
False
True

Root cause: Select-String matches one line at a time, so a pattern that spans a newline can never match. With -Raw you get one string: ^/$ then mean start/end of the whole string unless you add (?m). And on Windows Set-Content appended a CRLF, so the last line ends in \r and $ (which matches before \n) does not see ok directly before it.

Fix and prevention
$raw = Get-Content -LiteralPath $f -Raw
[regex]::Matches($raw, '(?ms)^server: (?<name>\S+)\r?\nstatus: (?<st>\w+)\r?$')
Select-String -Path $f -Pattern 'status: degraded' -Context 1, 0   # or keep line mode and look at context

Normalize line endings before matching ($raw -replace "`r`n", "`n") or allow \r? explicitly. Interview Q24.

How PowerShell evaluates an operator

Left operandscalar or collection? Collection → filter-eq -match -like return items #8 #16 Convert right → left type#13 '10' -lt 9 · culture #24 Regex?-match -replace -split #17 #18 Resultcase-insensitive #15 Culture: who uses which? Invariant: casts [datetime]'…' [double]'…', "$x", [string]$x Current: Get-Date -Date '…', .ToString(), -f, ::Parse() without culture #22 dates · #24 numbers Safe: ISO 8601 + InvariantCulture + ConvertTo-Json Output and cost Every uncaptured value is output (#21) += on arrays copies everything (#20) @{} unordered → [ordered] / [pscustomobject] (#19) Streaming read + write same file → lock (#23)
Figure 2-1: ask three questions of every operator — is the left side a collection, what type is it, and is this regex?

Operator evaluator

Pick an expression and watch the engine's decisions. Red marks the step that produces the surprise; the console shows the real 7.6.10 result.

Ready.

Goal: build a small, culture-safe and regex-safe log parser for access.log. Environment: pwsh 7.6, ~/pslab/lab9. Cost: none.

Lab 2-A · coercion (#13, #12). Count requests with more than 4000 bytes, first wrong, then right:
$lines = Get-Content ../data/access.log
@($lines | Where-Object { ($_ -split ' ')[9] -gt 4000 }).Count
@($lines | Where-Object { [int]($_ -split ' ')[9] -gt 4000 }).Count

The first line compares strings (“900” > “4000”), the second numbers. Verified on 7.6.10: 184 with the string comparison, 140 with the numeric one.

Lab 2-B · named groups instead of $Matches (#16).
$rx = [regex]'^(?<ip>\S+) .*?"(?<m>[A-Z]+) (?<path>\S+) HTTP/1\.1" (?<st>\d{3}) (?<bytes>\d+)'
$req = foreach ($l in [IO.File]::ReadLines((Resolve-Path ../data/access.log))) {
    $m = $rx.Match($l)
    if ($m.Success) { [pscustomobject]@{ IP = $m.Groups['ip'].Value; Status = [int]$m.Groups['st'].Value; Bytes = [int]$m.Groups['bytes'].Value } }
}
$req.Count; @($req | Where-Object Status -ge 500).Count; ($req | Measure-Object Bytes -Sum).Sum

Verified on 7.6.10: 611, 20, 2918056 — the dataset facts from Hour 1.

Lab 2-C · safe in-place edit (#23). Replace canadacentral with canadaeast in a copy of servers.csv using the temp-file pattern; confirm the row count is still 13 and the file is not empty.
Lab 2-D · culture test (#22, #24). Put [cultureinfo]::CurrentCulture = 'de-DE' at the top of Lab 2-B and run it again. The counts must not change. Then add '{0:N0}' -f $sum and see why reports should format at the very end.
Cleanup: Remove-Item ./servers.csv, ./status.txt -ErrorAction Ignore
Scenario questions
A teammate's function Get-Targets “sometimes returns numbers”. It uses an ArrayList and New-Item to create a work folder. What do you look for, and what single test would have caught it?

Uncaptured output (#21): $list.Add() returns the index, New-Item returns a DirectoryInfo. Discard with $null = or use List[T]. A Pester test asserting the output type and count (Get-Targets | Should-HaveType ([string]) / count equals the fixture size) catches it.

A templating script renders appsettings.json with -replace '{{DbPassword}}', $secret. A new password containing $1 breaks it. Why, and what is the robust fix?

The pattern is regex (braces are quantifier syntax) and the replacement is a substitution string ($1 is a group reference, $$ a dollar) (#17). Use .Replace() or, better, build the object and ConvertTo-Json -Depth it — never template JSON with string operations; and keep the secret out of the file if possible (Hour 7).

Verified teaching videos

▶
PowerShell Quiz & Quirks — PowerShell Conference Europe
English · operator and type quirks (#13–#18)
▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
English · scripting, data and text

No verified video covers culture-dependent parsing (#22, #24) or same-file rewrites (#23).

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: '10' -lt 9 → True; the right operand morphs into a string.
Narration: the left side decides the type.
Shot 2 · 30–60s
Visual: '10.30.1.41' -replace '.', '-' turns into dashes; a regex badge appears on -match, -replace, -split.
Narration: three operators are regex; escape or use the literal method.
Shot 3 · 60–90s
Visual: the same date string on an en-US and an en-GB machine; ISO 8601 resolves it.
Narration: casts are invariant, cmdlets and .NET methods use the current culture.
or score ≥ 70% on the Quiz

Module 3 · Part A: Errors, remoting and concurrency (issues 26–38)

16:00 – 24:00 · errors that try/catch never sees, preferences that leak or do not cross boundaries, native exit codes, objects that lose their methods across a process boundary, variables and functions that do not exist in another runspace, shared-state races, job output, default throttles and timeouts
8 minerror record → boundary → result13 issues★★★★★
Learning objectives
  • Explain which errors try/catch catches (#26), how $ErrorActionPreference is scoped (#27) and how native commands report failure (#28).
  • Name the boundaries that change data and visibility: process (jobs, remoting → serialization, #29), runspace (-Parallel, thread jobs → $using:, functions, #30, #32), machine (Kerberos double hop, TrustedHosts, #31, #37).
  • Make concurrency correct and fast: thread-safe results (#33), job output and errors (#34), throttle limits (#35), job types (#36), timeouts (#38).
Prerequisites: Modules 1–2; Hour 5 (errors) and Hour 6 (remoting and parallelism). Importance:★★★★★ (silent failures and races are the most expensive bugs in automation)

Filter by a keyword (catch, SilentlyContinue, exit code, Deserialized, using, double hop, not recognized, race, Receive-Job, ThrottleLimit, TrustedHosts, Timeout) and click a row.

#26 try { Get-Item $p } catch { … } — the catch block never runs (non-terminating errors)

Symptom: Error handling looks complete, but failures are only printed in red and the script continues — the “after” code runs on missing data, and the job reports success.

Reproduction
try   { Get-Item ./no-such-file.txt; 'after Get-Item' }
catch { 'caught' }
try   { Get-Item ./no-such-file.txt -ErrorAction Stop; 'after Get-Item' }
catch { "caught: $($_.Exception.GetType().Name)" }
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\lab9\no-such-file.txt' because it does not exist.
after Get-Item
caught: ItemNotFoundException

Root cause: Most cmdlet errors are non-terminating: written to the error stream and to $Error, then the pipeline continues. catch only receives terminating errors. -ErrorAction Stop (or $ErrorActionPreference = 'Stop') promotes them.

Fix
try {
    $item = Get-Item -LiteralPath $p -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Warning "missing: $p"; return
} catch {
    throw            # rethrow anything you did not expect
}
Prevention
  • In scripts: $ErrorActionPreference = 'Stop' at the top plus explicit -ErrorAction SilentlyContinue where a failure is expected.
  • Tests that feed a missing path and assert the function throws ({ … } | Should-Throw).

See Hour 5; interview Q26.

#27 After dot-sourcing a helper, errors disappear: “EAP is now: SilentlyContinue” ($ErrorActionPreference leaks — or does not cross into modules)

Symptom A (leak): a script sets $ErrorActionPreference = 'Stop', dot-sources a shared “library”, and from then on errors are swallowed. Symptom B (no crossing): the caller sets Stop, but functions from a script module still continue on errors.

Reproduction (A)
# ../snip/lib-quiet.ps1
# a "helper library" someone dot-sources
$ErrorActionPreference = 'SilentlyContinue'
function Get-Thing { 'thing' }
$ErrorActionPreference = 'Stop'
. ../snip/lib-quiet.ps1
"EAP is now: $ErrorActionPreference"
try { Get-Item ./no-such-file.txt; 'continued silently' } catch { 'caught' }
EAP is now: SilentlyContinue
continued silently

Root cause: Preference variables are ordinary variables with dynamic scope. Dot-sourcing runs the library in your scope, so its assignment overwrites yours. Conversely, a script module has its own session state: its functions look up $ErrorActionPreference in the module scope and the global scope, not in the caller's script scope — the same mechanism behind issue #50 (-WhatIf).

Fix and prevention
  • Libraries never set preference variables at file level; put settings inside functions ([CmdletBinding()] functions get -ErrorAction for free).
  • Pass -ErrorAction Stop explicitly when calling module functions whose failures must stop you, or have the module use $PSCmdlet.ThrowTerminatingError() for fatal conditions.
  • Prefer modules over dot-sourced files (Hour 4).

Interview Q27.

#28 $ErrorActionPreference = 'Stop', but a failing native command (git, az, kubectl, terraform) does not stop the script

Symptom: terraform plan or az deployment fails with exit code 1, the script continues and the next step deploys a half-baked state; “stderr” lines may or may not appear as red errors depending on redirection.

Reproduction
$ErrorActionPreference = 'Stop'
cmd /c "echo partial output & exit 5"
"still running, LASTEXITCODE=$LASTEXITCODE"
$PSNativeCommandUseErrorActionPreference = $true
try { cmd /c "exit 5"; 'not reached' }
catch { "$($_.Exception.GetType().Name): $($_.Exception.Message)" }
partial output 
still running, LASTEXITCODE=5
NativeCommandExitException: Program "cmd.exe" ended with non-zero exit code: 5 (0x00000005).

Root cause: Native programs report failure through their exit code, which PowerShell stores in $LASTEXITCODE; by default it does not raise an error. Since PowerShell 7.4, setting $PSNativeCommandUseErrorActionPreference = $true turns a non-zero exit code into a NativeCommandExitException that honours $ErrorActionPreference. Native stderr output is not an error indicator (many tools write progress to stderr).

Fix
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true      # 7.4+
# or explicitly, on any version:
terraform plan -out tf.plan
if ($LASTEXITCODE -ne 0) { throw "terraform plan failed ($LASTEXITCODE)" }
Prevention
  • Put both preference lines at the top of CI scripts; wrap tools with documented non-zero “success” codes (e.g. robocopy 1–7, terraform plan -detailed-exitcode 2) in a function that checks codes explicitly.

Interview Q28.

#29 Method invocation failed because [Deserialized.System.IO.FileInfo] does not contain a method named 'OpenText' (objects from jobs and remoting)

Symptom: Code that works locally fails when the data comes from Invoke-Command, Start-Job or Import-Clixml: methods are missing, nested properties are strings, type checks (-is [System.IO.FileInfo]) are false.

Reproduction
$local  = Get-Item ../data/servers.csv
$remote = Start-Job { Get-Item $using:local.FullName } | Receive-Job -Wait -AutoRemoveJob
$local.PSObject.TypeNames[0]
$remote.PSObject.TypeNames[0]
@($local  | Get-Member -MemberType Method).Count
@($remote | Get-Member -MemberType Method).Count
$remote.OpenText()
System.IO.FileInfo
Deserialized.System.IO.FileInfo
23
2
InvalidOperation: 
Line |
   7 |  $remote.OpenText()
     |  ~~~~~~~~~~~~~~~~~~
     | Method invocation failed because [Deserialized.System.IO.FileInfo] does not contain a method named 'OpenText'.

Root cause: Crossing a process boundary serializes objects to CLIXML. Most types come back as property bags with the type name prefixed by Deserialized.: properties (to a limited depth) but only ToString/GetType-style methods. Thread-based jobs and ForEach-Object -Parallel stay in-process and return live objects.

Fix and prevention
  • Do the method calls on the remote side and return plain data: Invoke-Command { (Get-Item $p).OpenText().ReadLine() }.
  • Return [pscustomobject] with exactly the properties you need; never test remote results with -is on live types.
  • Use thread jobs when you need live objects locally (and the work is local).

See Hour 6; interview Q43.

#30 Variables are empty inside ForEach-Object -Parallel / Start-ThreadJob / Invoke-Command (missing $using:)

Symptom: A parallel health check hits http:///healthz, uses an empty environment name, or deletes in the wrong place because a path variable is $null — no error at all.

Reproduction
$envName = 'prod'
1..2 | ForEach-Object -Parallel { "item $_ env=[$envName]" }
1..2 | ForEach-Object -Parallel { "item $_ env=[$using:envName]" }
Start-ThreadJob { "job env=[$envName]" } | Receive-Job -Wait -AutoRemoveJob
item 1 env=[]
item 2 env=[]
item 1 env=[prod]
item 2 env=[prod]
job env=[]

Root cause: Each parallel item runs in a separate runspace (jobs: a separate process or thread; remoting: another machine). Variables of the caller do not exist there; an undefined variable is $null. $using:name copies the value in (for -Parallel and thread jobs a reference to the same object; for processes and remoting a serialized copy).

Fix and prevention
$servers | ForEach-Object -Parallel { Test-Connection $_ -Count 1 -TimeoutSeconds $using:timeout }
Set-StrictMode -Version Latest   # inside the script block: an unknown variable becomes an error

PSScriptAnalyzer flags PSUseUsingScopeModifierInNewRunspaces for variables used in -Parallel, jobs and Invoke-Command blocks without $using: — enable it in CI. Interview Q45.

#31 Access is denied to \\fs01\share from inside Invoke-Command (Kerberos double hop)

Symptom: A remote script that copies a package from a file share, queries AD or calls another server works when run locally on the target (RDP) and fails through remoting with access denied or anonymous-logon errors.

Reproduction (needs a domain with two servers — not run for this lesson)
Invoke-Command -ComputerName web-01 -ScriptBlock { Get-ChildItem \\fs01\packages }
Get-ChildItem: Access to the path '\\fs01\packages' is denied.

Root cause: With default Kerberos authentication the remote session on web-01 has a network logon without delegable credentials, so it cannot authenticate onward to fs01 (the second hop).

Fix options (most to least preferred)
  • Avoid the second hop: push the file to the target first (Copy-Item -ToSession), or pull it on the local side and pass content.
  • Resource-based Kerberos constrained delegation on fs01 allowing web-01 (no CredSSP, scoped).
  • Pass a credential explicitly to the inner command (New-PSDrive -Credential $using:cred) from a secret store.
  • JEA endpoint with a virtual/gMSA account that has the needed rights.
  • CredSSP only as a last resort: it sends reusable credentials to the target.

Interview Q43. Not run: the lab has no domain (Known limitations).

#32 Get-Health: The term 'Get-Health' is not recognized … inside ForEach-Object -Parallel (functions do not travel)

Symptom: A refactor from foreach to -Parallel fails for every item with “not recognized”, although the function is defined two lines above.

Reproduction
function Get-Health([string]$Name) { "$Name OK" }
'web-01', 'api-01' | ForEach-Object -Parallel { Get-Health $_ }
$def = ${function:Get-Health}.ToString()
'web-01', 'api-01' | ForEach-Object -Parallel {
    ${function:Get-Health} = $using:def
    Get-Health $_
}
Get-Health: The term 'Get-Health' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Get-Health: The term 'Get-Health' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
web-01 OK
api-01 OK

Root cause: A new runspace starts with a fresh session state: no functions, variables or imported modules of the caller (modules can auto-load if they are on the PSModulePath). Functions are just definitions — you can pass their text with $using: and recreate them.

Fix and prevention
  • Best: put shared functions in a module (OpsKit) and Import-Module it inside the block — explicit and versioned.
  • Quick: pass the definition as a string (as above). Do not pass a ScriptBlock object via $using:: -Parallel rejects script-block variables to avoid cross-runspace state.
#33 Parallel counter says 1999 of 2000; “$using:total += $_” is a parse error (shared state and races)

Symptom: Totals in a parallel run are slightly too low and differ between runs; some results are missing; occasionally an exception from inside a collection.

Reproduction
$stats = [hashtable]::Synchronized(@{ Ok = 0 })
1..2000 | ForEach-Object -Parallel { ($using:stats).Ok++ } -ThrottleLimit 8
"synchronized hashtable ++ : $($stats.Ok) of 2000"
$bag = [System.Collections.Concurrent.ConcurrentBag[int]]::new()
1..2000 | ForEach-Object -Parallel { ($using:bag).Add($_) } -ThrottleLimit 8
"ConcurrentBag.Add         : $($bag.Count) of 2000"
$out = 1..2000 | ForEach-Object -Parallel { 1 } -ThrottleLimit 8
"collect output, then sum  : $(($out | Measure-Object -Sum).Sum) of 2000"
synchronized hashtable ++ : 1999 of 2000
ConcurrentBag.Add         : 2000 of 2000
collect output, then sum  : 2000 of 2000
$total = 0
1..3 | ForEach-Object -Parallel { $using:total += $_ }
MethodInvocationException: 
Line |
   4 |  . ([scriptblock]::Create($__c))
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "Create" with "1" argument(s): "At line:2 char:35
+ 1..3 | ForEach-Object -Parallel { $using:total += $_ }
+                                   ~~~~~~~~~~~~
The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property."

Root cause: $using: gives every runspace a reference to the same object. ++ is read–modify–write: two threads read 41, both write 42. A synchronized hashtable makes each single access thread-safe, not the sequence. Assigning to $using: is not allowed at all — values do not flow back.

Fix and prevention
  • Return results from the block and aggregate afterwards (third line of the reproduction) — no shared state.
  • If you must share: System.Collections.Concurrent types (ConcurrentBag, ConcurrentDictionary.AddOrUpdate) or [System.Threading.Interlocked]::Increment([ref]…) on a field.
  • Never List[T]/ArrayList/Hashtable writes from parallel blocks.

Interview Q45.

#34 Job “Completed” but its error was never seen; second Receive-Job returns nothing (job output is consumed)

Symptom: A nightly job reports success; the log has no errors; the data is incomplete. Or a debugging session shows output once and then “it vanished”.

Reproduction
$job = Start-Job { 'line 1'; Write-Error 'disk full'; 'line 2' }
$null = Wait-Job $job
$job.State
@(Receive-Job $job 2>$null).Count
@(Receive-Job $job 2>$null).Count
$job.ChildJobs[0].Error.Count
Remove-Job $job
Completed
2
0
1

Root cause: A job's state is Completed unless a terminating error ends it; non-terminating errors are stored in the child job's Error collection. Receive-Job removes results from the job by default (-Keep keeps them), and errors are re-emitted on the error stream of the caller — which our 2>$null discarded, like many log wrappers do.

Fix and prevention
$results = Receive-Job $job -Wait -ErrorVariable jobErr -ErrorAction Continue
if ($jobErr -or $job.ChildJobs.Error.Count) { throw "job $($job.Id) had $($jobErr.Count) error(s)" }
Remove-Job $job

Inside the job, use $ErrorActionPreference = 'Stop' so that real failures make the job Failed.

#35 ForEach-Object -Parallel is “only twice as fast” (default ThrottleLimit is 5)

Symptom: Checking 200 endpoints with -Parallel takes far longer than expected; CPU is idle.

Reproduction
$t = Measure-Command { 1..10 | ForEach-Object -Parallel { Start-Sleep -Seconds 1 } }
'default ThrottleLimit : {0:N1} s' -f $t.TotalSeconds
$t = Measure-Command { 1..10 | ForEach-Object -Parallel { Start-Sleep -Seconds 1 } -ThrottleLimit 10 }
'ThrottleLimit 10      : {0:N1} s' -f $t.TotalSeconds
default ThrottleLimit : 2.3 s
ThrottleLimit 10      : 1.5 s

Root cause: ForEach-Object -Parallel and Start-ThreadJob default to 5 concurrent runspaces; Invoke-Command -ComputerName defaults to 32 connections. Ten one-second items with 5 slots need two “waves” (~2 s plus startup).

Fix and prevention
  • Set -ThrottleLimit deliberately: I/O-bound work (HTTP, remoting) can go to 16–64; CPU-bound work ≈ number of cores; respect the target's rate limits.
  • Measure; for small, fast items the runspace overhead can make -Parallel slower than foreach.
#36 Start-Job adds seconds per job; a loop starting 200 jobs takes minutes and lots of memory

Symptom: Background work is slow to start and memory grows with one pwsh process per job.

Reproduction
$t1 = Measure-Command { 1..5 | ForEach-Object { Start-Job { 1 } } | Receive-Job -Wait -AutoRemoveJob }
$t2 = Measure-Command { 1..5 | ForEach-Object { Start-ThreadJob { 1 } } | Receive-Job -Wait -AutoRemoveJob }
'Start-Job x5       : {0,6:N0} ms' -f $t1.TotalMilliseconds
'Start-ThreadJob x5 : {0,6:N0} ms' -f $t2.TotalMilliseconds
Start-Job x5       :  2,407 ms
Start-ThreadJob x5 :    613 ms

Root cause: Start-Job starts a new pwsh process per job (startup, module loading, CLIXML serialization of results). Start-ThreadJob (module Microsoft.PowerShell.ThreadJob in 7.6) and -Parallel use threads in the same process.

Fix and prevention
  • Default to thread jobs / -Parallel; use Start-Job only when you need process isolation (a crashing native library, a different -PSVersion 5.1 via Windows PowerShell compatibility, memory isolation).
#37 Connecting to remote server 10.30.1.41 failed … the destination is in the TrustedHosts list (WinRM by IP, workgroup)

Symptom: Invoke-Command -ComputerName 10.30.1.41 or to a workgroup/non-domain server fails before running anything; colleagues “fix” it with TrustedHosts = '*'.

Reproduction (needs a WinRM target — not run for this lesson)
Invoke-Command -ComputerName 10.30.1.41 -Credential $cred -ScriptBlock { hostname }
OpenError: [10.30.1.41] Connecting to remote server 10.30.1.41 failed with the following error message :
The WinRM client cannot process the request. Default authentication may be used with an IP address under the
following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit
credentials are provided. …

Root cause: Kerberos needs a name with an SPN in the same/trusted domain; by IP or across workgroups WinRM falls back to NTLM, which does not authenticate the server. WinRM therefore requires HTTPS or an explicit TrustedHosts entry. '*' disables that protection for every host.

Fix and prevention
  • Use DNS names in the domain (Kerberos); or WinRM over HTTPS (port 5986) with a certificate; or SSH remoting (Invoke-Command -HostName … -UserName …), which works cross-platform with key authentication.
  • If TrustedHosts is unavoidable, list specific hosts (Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'web-01.lab' -Concatenate), managed by configuration management — never *.

Not run: the lab machine's WinRM configuration was not changed (Known limitations).

#38 A job hangs for hours on one slow API call; Wait-Job -Timeout “did not stop it” (no timeouts by default)

Symptom: The 02:00 job is still “Running” at 09:00; the next run overlaps; a deploy pipeline hits its own 6-hour limit.

Reproduction (start mock.ps1 first)
try { Invoke-RestMethod http://localhost:8089/slow -TimeoutSec 2 }
catch { "$($_.Exception.GetType().Name): $($_.Exception.Message)" }
$job = Start-ThreadJob { Start-Sleep -Seconds 30; 'done' }
Wait-Job $job -Timeout 2 | Out-Null
"after Wait-Job -Timeout 2: $($job.State)"
Stop-Job $job; "after Stop-Job: $($job.State)"; Remove-Job $job
TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing.
after Wait-Job -Timeout 2: Running
after Stop-Job: Stopped

Root cause: Invoke-RestMethod/Invoke-WebRequest default to no timeout (-ConnectionTimeoutSeconds, alias -TimeoutSec, and -OperationTimeoutSeconds are 0 = indefinite). Wait-Job -Timeout only stops waiting; the job keeps running until you Stop-Job it.

Fix and prevention
Invoke-RestMethod $uri -TimeoutSec 30 -OperationTimeoutSeconds 30
if (-not (Wait-Job $job -Timeout 300)) { Stop-Job $job; throw "job $($job.Id) timed out" }

Give every network call, job and pipeline step an explicit timeout; scheduled tasks also have “stop the task if it runs longer than”.

Boundaries: what crosses and what does not

Same runspace function call · dot-source · & scriptvariables: dynamic scope (#27 leak)live objects with methodserrors: stream + $Errormodule function: own session state→ caller's preferences invisible (#27 #50) New runspace, same process ForEach-Object -Parallel · Start-ThreadJobno caller variables → $using: (#30)no caller functions (#32)$using: = shared reference → races (#33)live objects come backdefault ThrottleLimit 5 (#35) Other process / machine Start-Job · Invoke-Command · sshCLIXML serialization → Deserialized.* (#29)$using: = serialized copyprocess start cost (#36)auth: double hop (#31), TrustedHosts (#37)errors in ChildJobs.Error (#34)
Figure 3-1: before debugging a parallel or remote bug, name the boundary the data crossed
Cmdlet errorWriteError (non-terminating) -ErrorAction / $EAPContinue · Stop · Silently… Stop → terminatingcatch runs (#26) Continue → stream onlyscript goes on Native exe: exit code$LASTEXITCODE · 7.4+ opt-in throw (#28)
Figure 3-2: try/catch only sees what has been turned into a terminating error

Error and runspace flow

Follow an error or a value across the engine and its boundaries. Red = where it is lost or changed. Logs are real 7.6.10 output.

Ready.

Goal: turn a fragile parallel health check into a correct one. Environment: pwsh 7.6, ~/pslab/lab9, mock.ps1 running. Cost: none.

Lab 3-A · the fragile version. Read it and list every issue number you can see before running it:
$base = 'http://localhost:8089'
$ok = 0
'reset', 'bad', 'slow', 'flaky' | ForEach-Object -Parallel {
    try { Invoke-RestMethod "$base/$_"; $ok++ } catch { }
}
"ok=$ok"

Verified on 7.6.10 it prints ok=0 with no error at all. Findings: $base without $using: (#30) — every URI becomes /reset, /bad … with no host, and the empty catch hides the resulting errors; $ok++ changes a variable that only exists in the runspace, so the caller still sees 0 (#33); no timeout (#38); default throttle (#35).

Lab 3-B · the corrected version.
$base = 'http://localhost:8089'
$null = Invoke-RestMethod "$base/reset"
$results = 'bad', 'slow', 'flaky', 'reset' | ForEach-Object -ThrottleLimit 16 -Parallel {
    $uri = "$($using:base)/$_"
    try {
        $r = Invoke-RestMethod $uri -TimeoutSec 2 -ErrorAction Stop
        [pscustomobject]@{ Uri = $uri; Ok = $true;  Detail = $r.status }
    } catch {
        [pscustomobject]@{ Uri = $uri; Ok = $false; Detail = $_.Exception.Message.Split("`n")[0] }
    }
}
$results | Sort-Object Uri | Format-Table -AutoSize
"ok=$(@($results | Where-Object Ok).Count) failed=$(@($results | Where-Object { -not $_.Ok }).Count)"
Uri                            Ok Detail
---                            -- ------
http://localhost:8089/bad   False Response status code does not indicate success: 400 (Bad Request).
http://localhost:8089/flaky False Response status code does not indicate success: 503 (Service Unavailable).
http://localhost:8089/reset  True ok
http://localhost:8089/slow  False The request was canceled due to the configured HttpClient.Timeout of 2 seconds elaps…

ok=1 failed=3

Results are returned, not shared; every call has a timeout; errors become data you can count and fail on.

Lab 3-C · jobs. Rewrite the reproduction of #34 so that the script throws when the job had an error (use -ErrorVariable), and make the job itself Failed by adding $ErrorActionPreference = 'Stop' inside it. Compare $job.State.
Cleanup: Get-Job | Remove-Job -Force; Invoke-RestMethod http://localhost:8089/stop
Scenario questions
A patch script runs Invoke-Command -ComputerName $servers { Install-Package … } and then if ($?) { 'all good' }. Three servers failed but the script printed “all good”. Explain and fix.

$? reflects only the last command's overall success; remote non-terminating errors arrive as error records tagged with PSComputerName. Use -ErrorVariable remoteErr and check it; return a result object per server ([pscustomobject]@{ Computer = $env:COMPUTERNAME; Ok = $true }) and compare the set of OK servers with the input list — unreachable servers produce no result at all.

Your parallel inventory sometimes has 499 of 500 rows. Where do you look first?

Shared state written from the parallel block (#33): $using:list.Add() or a counter. Return objects and collect the loop output instead; compare the counts of input and output and log the missing names.

or score ≥ 70% on the Quiz

Module 4 · Part A: Modules, cloud, CI and security (issues 39–50)

24:00 – 30:00 · which module version actually loads, what a manifest exports, how CI finds modules, which subscription a script talks to, where secrets end up, what execution policy does not do, bytes and line endings between editions and platforms, REST error bodies, retries, and -WhatIf that silently stops at a module boundary
6 minenvironment → module → identity → output12 issues★★★★★
Learning objectives
  • Prove which module and version a job loads (Get-Module -ListAvailable, Import-Module -MinimumVersion, $env:PSModulePath) — #39–#42.
  • Make cloud scripts target the right tenant and subscription explicitly (#43), keep secrets out of logs (#44), and know what the execution policy is for (#45).
  • Handle bytes correctly between Windows PowerShell 5.1, PowerShell 7 and Linux (#46, #47).
  • Call REST APIs robustly: error bodies, retries with backoff (#48, #49); make -WhatIf really safe (#50).
  • Use the triage tree for a failing CI or scheduled PowerShell job.
Prerequisites: Modules 1–3; Hour 4 (modules), Hour 7 (cloud and APIs), Hour 8 (CI). Importance:★★★★★

Filter by a keyword (Pester, edition, export, PSModulePath, subscription, transcript, policy, BOM, CRLF, 400, retry, WhatIf) and click a row.

#39 Tests fail with “Should-Be is not recognized” or v3-style output: Windows' in-box Pester 3.4.0 was loaded

Symptom: On a Windows agent, Invoke-Pester runs with Pester 3.4 semantics (no BeforeAll discovery, legacy Should Be syntax) or new assertions like Should-Be are “not recognized”; on Linux runners the same tests pass.

Reproduction
Get-Module Pester -ListAvailable | Select-Object Name, Version, ModuleBase
Import-Module Pester; "imported: $((Get-Module Pester).Version)"
[bool](Get-Command Should-Be -ErrorAction SilentlyContinue)
Remove-Module Pester
Save-PSResource -Name Pester -Path ./modules -TrustRepository -Quiet   # done once; no install scope touched
Import-Module ./modules/Pester -MinimumVersion 6.0
"imported: $((Get-Module Pester).Version)"
[bool](Get-Command Should-Be -ErrorAction SilentlyContinue)
Name   Version ModuleBase
----   ------- ----------
Pester 3.4.0   C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0
imported: 3.4.0
False
imported: 6.2.0
True

Root cause: Windows ships Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules, which is on pwsh's PSModulePath. A bare Import-Module Pester (or auto-loading via Invoke-Pester) picks the highest version it can find; if a newer one is not installed for that account/agent, 3.4.0 wins. Pester 5+ and 6 are a different engine (discovery and run phases), and 6 adds the Should-* assertion functions.

Fix
#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.0.0' }
Import-Module Pester -MinimumVersion 6.0.0 -ErrorAction Stop
# CI: install the pinned version into a job-local folder and put it first on PSModulePath
Save-PSResource Pester -Version 6.2.0 -Path ./.modules -TrustRepository
Prevention
  • Pin and check versions in the test bootstrap ((Get-Module Pester).Version printed in the CI log).
  • Do not uninstall the in-box copy; shadow it with a newer version instead.

See Hour 8; interview Q33.

#40 Module installed but “not found” in pwsh — or a Desktop-only module imports without complaint (editions and module paths)

Symptom A: Install-Module X -Scope CurrentUser was run in Windows PowerShell 5.1; in pwsh, Import-Module X says no valid module file was found. Symptom B: a module whose manifest says CompatiblePSEditions = 'Desktop' imports in pwsh and then fails at run time.

Reproduction
$env:PSModulePath -split [IO.Path]::PathSeparator | Select-Object -Unique
New-Item -ItemType Directory ./LegacyTool -Force | Out-Null
Set-Content ./LegacyTool/LegacyTool.psm1 'function Get-Legacy { "legacy" }'
New-ModuleManifest ./LegacyTool/LegacyTool.psd1 -RootModule LegacyTool.psm1 -CompatiblePSEditions Desktop -FunctionsToExport Get-Legacy
Import-Module ./LegacyTool -PassThru | Select-Object Name, CompatiblePSEditions
C:\Users\labadmin\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\7\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

Name       CompatiblePSEditions
----       --------------------
LegacyTool {Desktop}

Root cause: Each edition has its own user module folder: pwsh uses Documents\PowerShell\Modules, 5.1 uses Documents\WindowsPowerShell\Modules (not in the list above). The machine folder C:\Program Files\WindowsPowerShell\Modules and the System32 folder are shared, which is why old modules (Pester 3.4) leak into pwsh. CompatiblePSEditions is enforced only for modules loaded from the System32 module path; elsewhere it is metadata (the import above succeeded). For System32 modules that are Desktop-only, pwsh uses the Windows PowerShell compatibility session (implicit remoting, deserialized objects — #29).

Fix and prevention
  • Install with PSResourceGet from pwsh (Install-PSResource X -Scope CurrentUser) or save into a job folder; check with Get-Module X -ListAvailable | Select Name, Version, ModuleBase.
  • Test modules under both editions if you claim both; declare CompatiblePSEditions and PowerShellVersion truthfully.
#41 New function is “not recognized” after import; private helpers are suddenly public (FunctionsToExport)

Symptom: Someone adds Test-OpsEndpoint to the module; it works when they dot-source the .psm1 but not after Import-Module. Or, with '*', helpers appear in tab completion and become an accidental API; module auto-loading is slow.

Reproduction
New-Item -ItemType Directory ./OpsDemo -Force | Out-Null
Set-Content ./OpsDemo/OpsDemo.psm1 @'
function Get-OpsServer { 'servers' }
function Test-OpsEndpoint { 'endpoint ok' }   # added later, manifest not updated
function ConvertTo-InternalName { 'helper' }   # private helper
'@
New-ModuleManifest ./OpsDemo/OpsDemo.psd1 -RootModule OpsDemo.psm1 -FunctionsToExport Get-OpsServer
Import-Module ./OpsDemo -Force
(Get-Command -Module OpsDemo).Name
Test-OpsEndpoint
Update-ModuleManifest ./OpsDemo/OpsDemo.psd1 -FunctionsToExport '*'
Import-Module ./OpsDemo -Force
(Get-Command -Module OpsDemo).Name -join ', '
Get-OpsServer
Test-OpsEndpoint: 
Line |
  10 |  Test-OpsEndpoint
     |  ~~~~~~~~~~~~~~~~
     | The term 'Test-OpsEndpoint' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
ConvertTo-InternalName, Get-OpsServer, Test-OpsEndpoint

Root cause: The manifest's FunctionsToExport filters what the root module exports. An explicit list must be maintained; '*' exports everything (including helpers) and prevents PowerShell from knowing the commands without loading the module, which slows command discovery.

Fix and prevention
# OpsKit.psm1 (Hour 4 layout): dot-source Public/ and Private/, export only Public/
$public = Get-ChildItem $PSScriptRoot/Public/*.ps1
foreach ($f in $public + (Get-ChildItem $PSScriptRoot/Private/*.ps1)) { . $f.FullName }
Export-ModuleMember -Function $public.BaseName
# build step: write the same list into the manifest
Update-ModuleManifest ./OpsKit.psd1 -FunctionsToExport $public.BaseName

A Pester test: (Get-Command -Module OpsKit).Name equals the file names in Public/. Interview Q19.

#42 Import-Module: The specified module 'OpsDemo' was not loaded because no valid module file was found in any module directory (PSModulePath in CI and services)

Symptom: The job works on the build server when an admin runs it and fails under the agent's service account or in a container; or it loads a different version than expected.

Reproduction
$sep = [IO.Path]::PathSeparator
pwsh -NoProfile -Command 'Import-Module OpsDemo; Get-OpsServer'
$env:PSModulePath = (Resolve-Path .).Path + $sep + $env:PSModulePath   # this process + children only
pwsh -NoProfile -Command 'Import-Module OpsDemo; Get-OpsServer'
Import-Module: The specified module 'OpsDemo' was not loaded because no valid module file was found in any module directory.
Get-OpsServer: The term 'Get-OpsServer' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
servers

Root cause: Module auto-loading and Import-Module Name search only $env:PSModulePath, which is built from the current user's folder, the pwsh install folder and machine folders, plus whatever the environment adds. Modules installed with -Scope CurrentUser by one account are invisible to another; a CI image may not have them at all.

Fix and prevention
  • Make dependencies part of the job: Save-PSResource (or a RequiredModules restore step) into a repository-local folder, prepend it to $env:PSModulePath for the job, import by version.
  • Print $env:PSModulePath -split [IO.Path]::PathSeparator and Get-Module -ListAvailable for key modules at the start of every CI run.
  • Import by path in tests (Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force).
#43 Script changed resources in the wrong subscription (implicit Az context)

Symptom: A cleanup or deployment script run by an engineer (or an automation account with access to several subscriptions) acts on whatever subscription the context points to — often the one used last, or the first one alphabetically.

Reproduction (needs an Azure sign-in — not run for this lesson)
Connect-AzAccount                       # interactive, saved context
Get-AzContext | Select-Object Name, Subscription, Tenant
Get-AzResourceGroup | Where-Object ResourceGroupName -like 'rg-temp-*' | Remove-AzResourceGroup -Force
Name                                          Subscription                         Tenant
----                                          ------------                         ------
prod-platform (11111111-…) - ops@contoso.com  11111111-1111-1111-1111-111111111111 22222222-…

Root cause: Az cmdlets use the current context (account + tenant + subscription), which is persisted to disk between sessions by default (Enable-AzContextAutosave) and shared by all sessions of that user. Nothing in the script said which subscription it is for.

Fix and prevention
param([Parameter(Mandatory)][guid]$SubscriptionId, [switch]$WhatIf)
Connect-AzAccount -Identity -ErrorAction Stop | Out-Null          # managed identity in automation
$ctx = Set-AzContext -Subscription $SubscriptionId -ErrorAction Stop
Write-Information "Target: $($ctx.Subscription.Name) ($($ctx.Subscription.Id))" -InformationAction Continue
Get-AzResourceGroup -Name 'rg-temp-*' | Remove-AzResourceGroup -Force -WhatIf:$WhatIf
  • Subscription as a mandatory parameter, echo the target, -WhatIf first, least-privilege RBAC on the identity; in CI use Disable-AzContextAutosave -Scope Process.

Not run: no cloud sign-in on the lab machine (Known limitations). See Hour 7; interview Q44.

#44 Tokens appear in transcripts and CI logs (Start-Transcript, Write-Host, -Verbose)

Symptom: A security review finds API tokens in C:\Transcripts\… (organizations often enable transcription by Group Policy), in pipeline logs, or in shared screenshots.

Reproduction (fake token)
$token = 'ghp_FAKE0123456789abcdef'
Start-Transcript ./run.transcript.txt | Out-Null
Write-Host "Calling API with token $token"
Write-Verbose "Authorization: Bearer $token" -Verbose
Stop-Transcript | Out-Null
Select-String -Path ./run.transcript.txt -Pattern 'ghp_' | ForEach-Object Line
Import-Module PSReadLine
[Microsoft.PowerShell.PSConsoleReadLine]::GetDefaultAddToHistoryOption('$token = "ghp_FAKE0123"')
[Microsoft.PowerShell.PSConsoleReadLine]::GetDefaultAddToHistoryOption('$t = Get-Content ./t.txt')
Calling API with token ghp_FAKE0123456789abcdef
VERBOSE: Authorization: Bearer ghp_FAKE0123456789abcdef
Calling API with token ghp_FAKE0123456789abcdef
VERBOSE: Authorization: Bearer ghp_FAKE0123456789abcdef
MemoryOnly
MemoryAndFile

Root cause: A transcript records everything written to the host, including Write-Host, verbose and debug streams. Interpolating a secret into any message publishes it. PSReadLine's history is safer by default: its default handler keeps lines that look sensitive (token, password, secret, apikey, asplaintext…) in memory only (MemoryOnly) instead of writing them to the history file — but that protects only what you type, not script output.

Fix and prevention
  • Never put secrets in messages; log a fingerprint ($token.Substring(0,4) + '…') or nothing.
  • Keep secrets as SecureString/PSCredential from SecretManagement or the platform's secret store; pass them via parameters, not environment dumps; mark CI variables as secret so the platform masks them.
  • Scan logs and transcripts in CI for token patterns (e.g. ghp_, eyJ), and keep transcripts in an access-controlled location.
#45 “Execution policy is AllSigned, so unsigned code cannot run” — but Get-Content | Invoke-Expression runs it anyway (execution policy myths)

Symptom: Either a hardening plan relies on execution policy as a security boundary, or an automation fails with “running scripts is disabled on this system” and someone sets Unrestricted machine-wide.

Reproduction (process scope only — nothing persistent is changed)
Set-Content ./hello.ps1 -Value '"hello from a script"'
pwsh -NoProfile -ExecutionPolicy Restricted -Command './hello.ps1'
pwsh -NoProfile -ExecutionPolicy Restricted -Command 'Get-Content ./hello.ps1 -Raw | Invoke-Expression'
pwsh -NoProfile -ExecutionPolicy Restricted -Command 'Get-ExecutionPolicy -List | Where-Object Scope -eq Process'
./hello.ps1: File C:\Users\labadmin\pslab\lab9\hello.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.
hello from a script

  Scope ExecutionPolicy
  ----- ---------------
Process      Restricted

Root cause: Execution policy is a safety feature that prevents accidentally running scripts; it is not a security boundary. Any user can run the same code via -Command, Invoke-Expression or by pasting it. On Linux/macOS it is always Unrestricted.

Fix and prevention
  • For automation, -ExecutionPolicy Bypass on the command line is normal (process scope).
  • Real controls: Windows Defender Application Control / AppLocker (which put PowerShell into Constrained Language Mode for untrusted code), code signing with AllSigned where WDAC enforces it, file ACLs on script folders, JEA for delegated admin, script block logging for detection.

See Hour 1 Module 8; interview Q11.

#46 “café” in a report; a 5.1 script writes UTF-16 files that Linux tools reject (encodings between 5.1 and 7)

Symptom: Non-ASCII names (users, sites, file names) become mojibake when a file written by pwsh is read by Windows PowerShell 5.1, or a file written by 5.1 with > contains NUL bytes for grep/git and shows as binary.

Reproduction
Set-Content ./cafe.txt -Value 'café-ünïcode'                     # pwsh 7: UTF-8, no BOM
powershell.exe -NoProfile -Command 'Get-Content ./cafe.txt'       # Windows PowerShell 5.1 reads it as ANSI
powershell.exe -NoProfile -Command 'Get-Content ./cafe.txt -Encoding UTF8'
powershell.exe -NoProfile -Command '"web-01" > ./from51.txt'
(Format-Hex ./from51.txt).Bytes[0..5] -join ' '
Get-Content ./from51.txt
Set-Content ./cafe-bom.txt -Value 'café-ünïcode' -Encoding utf8BOM
powershell.exe -NoProfile -Command 'Get-Content ./cafe-bom.txt'
café-ünïcode
café-ünïcode
255 254 119 0 101 0
web-01
café-ünïcode
# what Windows PowerShell 5.1 shows on a machine whose ANSI code page is 1252 (the common default)
[IO.File]::ReadAllText("$PWD/cafe.txt", [Text.Encoding]::GetEncoding(1252))
café-ünïcode

Root cause: pwsh writes UTF-8 without BOM by default. Windows PowerShell 5.1 reads BOM-less files with the ANSI code page. On the lab machine the code page is 65001 (the Windows “Beta: use Unicode UTF-8” option), so 5.1 happened to read it correctly; on the common default (1252) the same bytes decode as café-ünïcode (second block). 5.1's > writes UTF-16 LE with BOM (bytes 255 254 and a 0 after each ASCII character). A UTF-8 BOM makes both editions agree.

Fix and prevention
  • Files that 5.1 must read (including .ps1 files with non-ASCII string literals): -Encoding utf8BOM. Files for Linux tools, Git and web: UTF-8 without BOM (pwsh default).
  • In 5.1 code, always pass -Encoding UTF8 to Get-Content/Set-Content/Out-File; avoid > for files others read.
  • .editorconfig / VS Code files.encoding per file type; PSScriptAnalyzer rule PSUseBOMForUnicodeEncodedFile.
#47 Host list “web-01” does not equal “web-01”; scripts from Windows break on Linux (CRLF line endings)

Symptom: Comparisons fail although the text looks identical; the length is one character too long; on Linux, a script with a shebang fails with /usr/bin/env: 'pwsh\r': No such file or directory.

Reproduction
[IO.File]::WriteAllText("$PWD/hosts.txt", "web-01`r`napi-01`r`n")   # file checked out with CRLF
$raw = Get-Content ./hosts.txt -Raw
$names = $raw -split "`n" | Where-Object { $_ }
$names[0] -eq 'web-01'
$names[0].Length
($raw -split '\r?\n' | Where-Object { $_ })[0] -eq 'web-01'
(Get-Content ./hosts.txt)[0] -eq 'web-01'
Set-Content ./out.txt -Value 'a', 'b'
(Format-Hex ./out.txt).Bytes -join ' '
False
7
True
True
97 13 10 98 13 10

Root cause: Splitting a Windows file on "`n" leaves a trailing \r (length 7, not 6). Get-Content without -Raw splits on CR, LF and CRLF, so it is safe. Writers use the platform newline: Set-Content on Windows wrote 13 10 (CRLF) after each line.

Fix and prevention
  • Split with '\r?\n' or use Get-Content / [IO.File]::ReadLines(); .Trim() values from external files.
  • .gitattributes: *.ps1 text eol=lf (pwsh is happy with LF on Windows) and *.sh text eol=lf; when the exact bytes matter, write with ($lines -join "`n") + "`n" and -NoNewline.
#48 Invoke-RestMethod: Response status code does not indicate success: 400 (Bad Request) — and the API's explanation is lost

Symptom: Deployment logs only say “400 (Bad Request)”; the useful part ("SKU Standard_X9 is not available in canadacentral") is never logged, so every failure needs a manual rerun.

Reproduction (start mock.ps1 first)
try { Invoke-RestMethod http://localhost:8089/bad -Method Post -Body '{}' }
catch {
    "Status : $([int]$_.Exception.Response.StatusCode)"
    "Message: $($_.Exception.Message)"
    "Details: $($_.ErrorDetails.Message)"
}
$r = Invoke-RestMethod http://localhost:8089/bad -Method Post -Body '{}' -SkipHttpErrorCheck -StatusCodeVariable sc
"$sc $($r.error): $($r.message)"
Status : 400
Message: Response status code does not indicate success: 400 (Bad Request).
Details: 
{
  "error": "InvalidSku",
  "message": "SKU Standard_X9 is not available in canadacentral"
}
400 InvalidSku: SKU Standard_X9 is not available in canadacentral

Root cause: In PowerShell 7 the exception (HttpResponseException) carries the status in $_.Exception.Response.StatusCode and the response body in $_.ErrorDetails.Message; the exception message is generic. Logging only $_.Exception.Message drops the body.

Fix and prevention
  • In a shared wrapper (OpsKit's Invoke-OpsApi, Hour 7), log status, method, URI (without secrets), the request id header and ErrorDetails.Message (parsed with ConvertFrom-Json when possible).
  • For APIs where non-2xx is normal (404 = “not found”), use -SkipHttpErrorCheck -StatusCodeVariable sc and branch on $sc.
#49 Retries make an outage worse (no backoff, no jitter, retrying 400s) — and [math]::Min(30, 0.5) is 0

Symptom: During an API incident, hundreds of jobs retry every second in lockstep; the API's rate limiter blocks the whole tenant; retries of a 400 never succeed but delay the failure.

Reproduction (start mock.ps1 first; /flaky returns 503 three times)
$null = Invoke-RestMethod http://localhost:8089/reset
$r = Invoke-RestMethod http://localhost:8089/flaky -MaximumRetryCount 5 -RetryIntervalSec 1
"built-in retry: $($r.status)"
$null = Invoke-RestMethod http://localhost:8089/reset
function Invoke-WithBackoff([scriptblock]$Action, [int]$Max = 5, [double]$BaseSec = 0.5) {
    for ($i = 1; ; $i++) {
        try { return & $Action }
        catch {
            $code = [int]$_.Exception.Response.StatusCode
            if ($i -ge $Max -or $code -notin 429, 500, 502, 503, 504) { throw }
            $delay = [math]::Min(30.0, $BaseSec * [math]::Pow(2, $i - 1)) + (Get-Random -Minimum 0 -Maximum 0.25)
            Write-Warning ("attempt {0} got {1}; retrying in {2:N2}s" -f $i, $code, $delay)
            Start-Sleep -Seconds $delay
        }
    }
}
(Invoke-WithBackoff { Invoke-RestMethod http://localhost:8089/flaky }).status
built-in retry: ok
WARNING: attempt 1 got 503; retrying in 0.67s
WARNING: attempt 2 got 503; retrying in 1.19s
WARNING: attempt 3 got 503; retrying in 2.05s
ok
# built-in retry (-MaximumRetryCount 5 -RetryIntervalSec 1): fixed spacing
21:16:31.460 /flaky
21:16:32.636 /flaky
21:16:33.798 /flaky
21:16:34.980 /flaky
# Invoke-WithBackoff: growing spacing + jitter
21:16:35.404 /flaky
21:16:36.273 /flaky
21:16:37.656 /flaky
21:16:39.967 /flaky

Root cause: Fixed-interval retries (the built-in -MaximumRetryCount/-RetryIntervalSec retries at a constant interval) synchronize clients. Retrying non-transient codes (400, 401, 403, 404) only delays failure. Found while writing this lesson: the first version of the function used [math]::Min(30, …); PowerShell chose the Min(int, int) overload, rounded 0.5 to 0 (to even, #14) and the first delay was ~0 s. 30.0 forces the double overload.

Fix and prevention
  • Exponential backoff with a cap and jitter; retry only transient codes (408, 429, 5xx) and network errors; honour Retry-After on 429/503.
  • Make the operation idempotent (PUT with a known id, client request ids) before you retry writes.
  • Use the built-in retry only for simple reads; it retries 304 and 400–599 codes at a fixed interval.

Interview Q31.

#50 Invoke-Cleanup -WhatIf deleted files anyway (WhatIf does not cross module or .NET boundaries)

Symptom: A change reviewer runs the cleanup with -WhatIf to preview, and the files are gone. The outer function declares SupportsShouldProcess, so everyone assumed it was safe.

Reproduction (only inside ~/pslab/lab9/scratch)
New-Item -ItemType Directory ./CleanMod -Force | Out-Null
Set-Content ./CleanMod/CleanMod.psm1 @'
function Remove-OpsTemp {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Path)
    Get-ChildItem -LiteralPath $Path -Filter *.tmp | Remove-Item
}
'@
Import-Module ./CleanMod -Force
function Invoke-Cleanup {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Path)
    $Path = (Resolve-Path -LiteralPath $Path).Path
    Remove-OpsTemp -Path $Path                         # module function
    [IO.File]::Delete((Join-Path $Path 'b.log'))       # .NET call
}
New-Item -ItemType Directory ./scratch -Force | Out-Null
'a.tmp', 'b.log' | ForEach-Object { Set-Content (Join-Path ./scratch $_) 'x' }
Invoke-Cleanup -Path ./scratch -WhatIf
"left after -WhatIf: $((Get-ChildItem ./scratch).Name -join ', ')"
left after -WhatIf:

Root cause: -WhatIf sets $WhatIfPreference in the outer function's scope. The module function Remove-OpsTemp runs in the module's session state and does not see the caller's variable (same mechanism as #27), so its Remove-Item really deletes. A .NET method such as [IO.File]::Delete() knows nothing about ShouldProcess at all.

Fix (verified)
Import-Module ./CleanMod -Force
function Invoke-Cleanup {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Path)
    Remove-OpsTemp -Path $Path -WhatIf:$WhatIfPreference -Confirm:$false
    $f = Join-Path $Path 'b.log'
    if ($PSCmdlet.ShouldProcess($f, 'Delete')) { [IO.File]::Delete($f) }
}
'a.tmp', 'b.log' | ForEach-Object { Set-Content (Join-Path ./scratch $_) 'x' }
Invoke-Cleanup -Path ./scratch -WhatIf
"left after -WhatIf: $((Get-ChildItem ./scratch).Name -join ', ')"
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\lab9\scratch\a.tmp".
What if: Performing the operation "Delete" on target ".\scratch\b.log".
left after -WhatIf: a.tmp, b.log
Prevention
  • Pass -WhatIf:$WhatIfPreference (and -Confirm) explicitly to commands from other modules; guard every non-cmdlet side effect (.NET, REST, native tools) with $PSCmdlet.ShouldProcess().
  • A Pester test for every destructive public function: run it with -WhatIf on a fixture folder and assert nothing changed.

See Hour 5: safe change; interview Q17.

What a CI or scheduled PowerShell job depends on

Runner / accountedition · profile #6 · policy #45 PSModulePath#40 #42 Import-Moduleversion #39 · exports #41 Identity / context#43 subscription Script bodyREST #48 #49 · WhatIf #50 Bytes in, bytes out pwsh 7: UTF-8 no BOM · 5.1: ANSI read, UTF-16 for > (#46) Windows writers: CRLF · Linux: LF (#47) .gitattributes · -Encoding · -NoNewline Show-L9Bytes / Format-Hex to see them Where secrets leak (#44) transcripts (incl. GPO transcription) Write-Host / -Verbose / -Debug messages CI logs of command lines and env dumps files written with Export-Clixml on Linux (no DPAPI)
Figure 4-1: walk the chain left to right when a job fails only in CI

CI job simulator

Choose a failing job and step through the run: which stage silently loads the wrong thing or leaks something. Below it is the interactive triage tree.

Ready.

Interactive triage tree: a PowerShell job in CI / Task Scheduler failed (or silently did nothing)

Goal: make a CI bootstrap that is immune to issues #39–#42 and test -WhatIf safety. Environment: pwsh 7.6, network to the PowerShell Gallery. Cost: none.

Lab 4-A · job-local modules (#39, #42). Write bootstrap.ps1:
$mods = Join-Path $PSScriptRoot 'modules'
if (-not (Test-Path "$mods/Pester/6.2.0")) { Save-PSResource Pester -Version 6.2.0 -Path $mods -TrustRepository -Quiet }
$env:PSModulePath = $mods + [IO.Path]::PathSeparator + $env:PSModulePath
Import-Module Pester -MinimumVersion 6.0.0 -ErrorAction Stop
"Pester $((Get-Module Pester).Version) from $((Get-Module Pester).ModuleBase)"
Invoke-L9Clean '& ./bootstrap.ps1'
Pester 6.2.0 from C:\Users\labadmin\pslab\lab9\modules\Pester\6.2.0
(exit=0)

The version is 6.2.0 from the job folder regardless of what is installed for your user.

Lab 4-B · export contract (#41). In the OpsDemo folder from the reproduction, move each function to Public/ or Private/, generate the export list from file names (fix block of #41) and write the Pester test that compares Get-Command -Module OpsDemo with Public/*.ps1.
Lab 4-C · WhatIf test (#50). Write a Pester test for Invoke-Cleanup: create files in $TestDrive, call with -WhatIf, assert both files still exist. Run it against the broken and the fixed version from the reproduction.
Lab 4-D · bytes (#46, #47). With Show-L9Bytes, compare a file written by Set-Content, by Set-Content -Encoding utf8BOM and by [IO.File]::WriteAllText(). Which ones start with EF BB BF, which end with \r \n?
Cleanup: Clear-L9 (removes sandbox, modules, OpsDemo, LegacyTool, CleanMod, scratch); stop mock.ps1.
Scenario questions
A nightly Azure cleanup runbook deleted a resource group in production. It was written for the dev subscription and tested there. List the controls you would add.

Mandatory -SubscriptionId and explicit Set-AzContext, echo of the target in the log (#43); a managed identity with RBAC only on dev; a name/tag allow-list (env=dev, rg-temp-*); -WhatIf mode used in the PR pipeline (and propagated, #50); resource locks on production; alerting on deletions.

A security scan of build logs found a GitHub token. The script never calls Write-Host with it. Where else could it come from?

-Verbose/-Debug output of a function that logs headers; Set-PSDebug -Trace or Set-StrictMode errors that print the statement with the literal; transcripts; exception messages containing the URI with a token in the query string; CI “print environment” steps; git remote -v with credentials in the URL (#44).

Verified teaching videos

▶
PowerShell 7 Tutorials for Intermediates #5 : Pester (Testing) — JackedProgrammer
English · Pester basics (#39)
▶
PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training
English · modules, advanced functions (#41, #50)

No verified video covers in-box Pester 3.4 vs current Pester, PSModulePath on CI agents, encodings between 5.1 and 7, or -WhatIf across module boundaries; the reproductions in this module are the primary material. Older Pester videos use Pester 4/5 syntax.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: two Pester boxes, 3.4.0 (Windows) and 6.2.0 (job folder); PSModulePath order decides.
Narration: prove the version you load.
Shot 2 · 30–60s
Visual: a terminal with the subscription name in red; Set-AzContext pins it.
Narration: never let the context decide.
Shot 3 · 60–90s
Visual: -WhatIf stops at the module wall; -WhatIf:$WhatIfPreference passes through.
Narration: preview must be tested, not assumed.
or score ≥ 70% on the Quiz

Module 5 · Part B: Engine and fundamentals (interview Q1–13)

30:00 – 37:00 · what happens when you press Enter, editions, command resolution, pipeline binding, formatting, streams, parsing modes, scopes, $null and collections, execution policy, exit codes, providers
7 minmechanism → code → production story13 questions★★★★★
Learning objectives
  • Draw the engine on a whiteboard: parser → AST → command discovery → parameter binding → pipeline (begin/process/end) → Out-Default; place every Part A issue on it.
  • Answer “why” questions with a mechanism and a two-line demo, not with folklore.
  • Recognize the red flags interviewers listen for: “PowerShell pipes text”, “execution policy is our security”, “$? is the exit code”.
Prerequisites: Part A or Hour 1. Importance:★★★★★ (fundamentals decide whether the rest of the interview goes deep)

Scan the questions, mark the ones you are unsure of, click a row to open the model answer.

Q1. You type Get-ChildItem ./data | Where-Object Length -gt 1KB | Sort-Object Length and press Enter. What does PowerShell do until the table appears?Mid
30-second answer

The host hands the line to the engine. The parser builds an AST (a pipeline of three commands with their arguments). For each command, command discovery resolves the name (alias → function → cmdlet → external; modules auto-load). The parameter binder binds named and positional arguments, then the pipeline runs: all begin blocks, then each object flows one at a time through process (pipeline binding ByValue/ByPropertyName), then end blocks. Sort-Object collects everything and emits in its end block. The host appends Out-Default, which looks up the format view for FileInfo and renders text.

Mechanism and code
[System.Management.Automation.Language.Parser]::ParseInput('Get-ChildItem ./data | Sort-Object Length', [ref]$null, [ref]$null).EndBlock.Statements[0].PipelineElements.Count   # 2
Trace-Command -Name ParameterBinding -Expression { Get-Item ./data/servers.csv | Get-Content -TotalCount 1 } -PSHost
Get-Command Where-Object -All | Select-Object CommandType, Source
  • Streaming: Where-Object emits as soon as an item matches; Sort-Object, Group-Object, Measure-Object are blocking.
  • Formatting happens only at the end (issue #1).
Follow-ups
  • Where would -Filter help? Filtering in the provider (filter left) avoids creating objects that are dropped later.
  • What if Where were a function in your profile? Functions beat cmdlets in precedence (Q3).
Red flags

“PowerShell passes text between commands like Bash”; “Sort-Object sorts as items arrive”.

See Hour 1 Modules 4–6; issues #1, #9.

Q2. PowerShell 7.6 vs Windows PowerShell 5.1: what differs, and when do you still need 5.1?Junior
30-second answer

Different products installed side by side: pwsh (7.x, .NET 10, cross-platform, actively developed, LTS 7.6 until Nov 2028) and powershell.exe (5.1, .NET Framework, Windows only, security fixes only). They have separate profile and user module folders, different default encodings (UTF-8 without BOM vs ANSI/UTF-16), and 7 adds -Parallel, ternary and null-coalescing operators, SSH remoting, $PSNativeCommandUseErrorActionPreference and better native argument passing. 5.1 is still needed for a few Windows modules that never moved to .NET Core (some older RSAT/vendor modules) — usually via the Windows PowerShell compatibility feature or a 5.1 job.

Mechanism and code
$PSVersionTable.PSEdition                     # Core vs Desktop
Import-Module SomeLegacyModule -UseWindowsPowerShell   # proxy through a 5.1 session (objects come back deserialized)
#Requires -PSEdition Core
Follow-ups
  • What breaks when migrating? Encoding (#46), removed cmdlets (*-WmiObject → *-CimInstance), aliases like curl (#4), Out-File/> defaults, module availability (#40). See Q48.
Red flags

“PowerShell 7 is just 5.1 with new features, same modules folder”; not knowing that 7.4/7.5 are already out of support.

Q3. How does PowerShell decide what to run for a name like Get-Content or sort? How do you force the real cmdlet?Junior
30-second answer

Without a path: alias → function (and filter) → cmdlet → external (scripts and executables on PATH; never the current folder). With several modules exporting the same cmdlet name, the most recently imported wins. A module-qualified name (Microsoft.PowerShell.Management\Get-Content) bypasses aliases and functions; & (Get-Command x -CommandType Application) picks the executable.

Get-Command sort -All | Select-Object CommandType, Name, Source
Microsoft.PowerShell.Utility\Sort-Object -InputObject 3,1,2
Follow-ups
  • Why does sort differ on Linux? The alias is not defined there; /usr/bin/sort runs (#4).
  • How can this be a security issue? A malicious module or profile can shadow a cmdlet with a function — use module-qualified names in sensitive scripts and control the module path.
Red flags

“The cmdlet always wins”; “PowerShell searches the current directory first”.

Q4. Explain pipeline parameter binding (ByValue vs ByPropertyName) and how you debug a binding problem.Mid
30-second answer

For each incoming object the binder first tries parameters that accept ValueFromPipeline (the whole object, matching type — first without, then with type conversion), then ValueFromPipelineByPropertyName (a property whose name or alias matches a parameter). Example: a FileInfo piped to Get-Content binds through its PSPath property to -LiteralPath (alias PSPath), which is why piped files with brackets work (#2). Debug with Trace-Command -Name ParameterBinding.

Trace-Command ParameterBinding { Get-Item './data/[draft] notes.md' -ErrorAction Ignore | Get-Content } -PSHost
Get-Help Get-Content -Parameter LiteralPath   # "Accept pipeline input? True (ByPropertyName)"
Follow-ups
  • Design question: which should your own function use? ByPropertyName for objects from other commands (ComputerName, Name), ByValue for the “main” input type (Q15).
  • What is a delay-bind script block? Rename-Item -NewName { $_.Name -replace … }: a script block bound to a pipeline-enabled parameter is evaluated per object.
Red flags

“It matches by position”; never having used Trace-Command or Get-Help -Parameter.

Q5. Why must Format-* cmdlets come last? What does Out-Default do?Junior
30-second answer

Format-Table/-List convert objects into format records describing how to draw them; subsequent commands receive those records, not your data (issue #1). Every pipeline typed at the prompt ends in an implicit Out-Default, which chooses a view (format.ps1xml, DefaultDisplayPropertySet, or table for ≤4 properties / list otherwise) and sends text to the host.

Get-Process -Id $PID | Format-Table Id, Name | Get-Member | Select-Object -First 1 -ExpandProperty TypeName
# Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Follow-ups
  • When is Out-String legitimate? To put a rendered table into an email body or log line — at the end, knowingly.
  • How do you make your object display nicely without formatting it? A format file with a table view, or DefaultDisplayPropertySet via Update-TypeData.
Red flags

Returning Format-Table output from functions “because it looks better”.

Q6. Name PowerShell's output streams. When do you use Write-Host, Write-Output, Write-Verbose, Write-Information?Mid
30-second answer

1 Success (output), 2 Error, 3 Warning, 4 Verbose, 5 Debug, 6 Information; *> redirects all. Data goes to success (implicitly or Write-Output). Diagnostics go to Verbose/Debug (off by default, enabled by -Verbose). User-facing progress messages use Information (Write-Information, controllable with -InformationAction). Write-Host since 5.0 writes to the Information stream with a host tag — fine for interactive UX, wrong for data.

$r = & { Write-Host 'ui'; Write-Information 'info'; 'data' } 6>$null   # $r = 'data'; both messages suppressed
./job.ps1 *> ./job.log                                                  # everything into a file
Follow-ups
  • Why is Write-Output rarely needed? Any uncaptured value is output — which is also why issue #21 happens.
  • How do streams look in CI? Warnings and errors are visible; verbose is not — log what matters to Information.
Red flags

“Write-Host cannot be captured or redirected at all” (outdated since 5.0); using Write-Host to return values.

Q7. Expression mode vs argument mode: why does Write-Output 1+1 print “1+1”? How do quoting rules work?Mid
30-second answer

After a command name, the parser reads in argument mode: bare tokens are strings, $var and ( )/$( ) are evaluated, a leading - starts a parameter. At the start of a statement and inside parentheses it reads in expression mode (numbers, operators). Single quotes are literal; double quotes expand $var and $( ) only (#3); the escape character is the backtick; here-strings for multi-line text; --% stops parsing for native commands.

Write-Output 1+1          # 1+1
Write-Output (1+1)        # 2
"Total: $($a.Count + 1)"
Follow-ups
  • Why did a -join in an argument break? In argument mode -join is a parameter name; wrap the expression in parentheses (Hour 1 integrated lab).
  • Native arguments with quotes? 7.3+ passes arguments faithfully ($PSNativeCommandArgumentPassing); on Windows some legacy tools need the Windows mode.
Red flags

Fixing quoting problems by adding backticks until it works.

Q8. Explain scopes: global, script, local, private, module. What does dot-sourcing change?Mid
30-second answer

Scopes nest dynamically: a function or script gets a new child scope; reading a variable walks up the parent chain, writing creates a local copy unless you use a scope modifier ($script:x, $global:x). $private:x hides it from children. Dot-sourcing runs a script in the caller's scope (functions and variables stay — and assignments overwrite, issue #27). A module has its own session state: its functions see module variables and globals, not the caller's script variables — the root of issues #27 and #50.

$x = 1; function f { $x = 2; "in f: $x" }; f; "after: $x"      # in f: 2 / after: 1
function g { $script:counter++ }                                # explicit
Follow-ups
  • Why avoid $global:? Hidden coupling, leaks between tests and runs.
  • Runspaces? A new runspace has no relation to these scopes at all (#30, #32).
Red flags

“Functions see all my variables, including inside modules”.

Q9. Why should $null be on the left of a comparison? What does @(1,$null,2) -eq $null return?Junior
30-second answer

With a collection on the left, comparison operators filter; the result is the matching elements, and its truthiness depends on those elements. @(1,$null,2) -eq $null returns an array containing one $null — falsy — so an if says “no null” (issue #8). $null -eq $x is a scalar comparison and always returns a bool.

$empty = @()
$null -eq $empty
($empty -eq $null).GetType().Name, ($empty -eq $null).Count
$x = $null; $x.Count; (5).Count
function Get-Two { 'a', 'b' }; function Get-OneArray { , @('a') }
(Get-Two).GetType().Name; (Get-OneArray).GetType().Name
False
Object[]
0
0
1
Object[]
Object[]
Follow-ups
  • What is $null.Count? 0 (and a scalar's .Count is 1) since PowerShell 3 — but under Set-StrictMode -Version Latest both throw “The property 'Count' cannot be found on this object” (verified on 7.6.10). @($x).Count works in every mode.
  • How do you keep a one-element array from unrolling? The unary comma (, @('a')) — last two lines.
Red flags

Not knowing the filter behaviour; “PSScriptAnalyzer warnings about null comparisons are style only”.

Q10. What is pipeline unrolling? How do @( ), the comma operator and -InputObject change it?Mid
30-second answer

When a collection is written to the pipeline, it is enumerated: each element becomes a separate object; the caller collects 0 items as $null, one item as the item, more as Object[] (#9). @( ) at the consumer forces an array. , $x wraps the collection in a one-element array so that unrolling yields the collection itself. Parameters like -InputObject receive the collection as a whole, which is why Get-Member -InputObject $arr describes Object[] while $arr | Get-Member describes the elements.

@(Get-ChildItem ./data -Filter *.nope).Count     # 0, not an error
ConvertTo-Json -InputObject @($one) -Compress     # always a JSON array
Follow-ups
  • Which types are not unrolled? Strings and hashtables are enumerable in .NET but treated as scalars by the pipeline (use .GetEnumerator() for hashtables).
Red flags

Fixing 0/1/many bugs with if ($x -is [array]) branches everywhere.

Q11. What is the execution policy for? Is RemoteSigned a security control?Junior
30-second answer

A safety feature on Windows that prevents accidentally running scripts (e.g. a downloaded file with a Zone.Identifier mark under RemoteSigned). It is not a security boundary: -ExecutionPolicy Bypass, Invoke-Expression or pasting the content all work (issue #45). Scopes: MachinePolicy, UserPolicy (GPO), Process, CurrentUser, LocalMachine. Real controls are WDAC/AppLocker (with Constrained Language Mode), signing enforced by those, ACLs on script folders, JEA, and logging (script block logging, transcription).

Get-ExecutionPolicy -List
$ExecutionContext.SessionState.LanguageMode     # FullLanguage / ConstrainedLanguage
Follow-ups
  • Why does CI use Bypass? The process-scope setting avoids failures without weakening anything that was a boundary.
Red flags

“We set Restricted, so attackers cannot use PowerShell”; setting Unrestricted for LocalMachine to “fix” a job.

Q12. $?, $LASTEXITCODE, exit, pwsh -File vs -Command: how does a scheduler learn that your script failed?Mid
30-second answer

$? is a bool: did the last statement succeed. $LASTEXITCODE is the exit code of the last native program or script that called exit N. The process exit code that a scheduler sees: with -File, the script's exit N (1 if it threw); with -Command, only 0/1 from the last statement (issue #5). An unhandled terminating error under -File gives exit code 1.

pwsh -NoProfile -NonInteractive -File ./job.ps1; $LASTEXITCODE
# in the script: return objects; exit 0 ok / 1 failure / 2 usage (Hour 1 convention)
Follow-ups
  • Why does GitHub Actions' shell: pwsh work? It appends if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE } and uses $ErrorActionPreference = 'stop'.
  • Native tools? See issue #28.
Red flags

“$? is the exit code”; using return 3 in a script to signal failure to a scheduler.

Q13. What are providers and PSDrives? Why do -Path and -LiteralPath both exist?Junior
30-second answer

Providers expose data stores through the same item cmdlets: FileSystem, Registry (HKLM:), Env (env:), Variable, Function, Alias, Certificate (Windows), WSMan. A PSDrive is a named root on a provider. Item cmdlets accept -Path (with wildcard expansion done by the provider) and -LiteralPath (no wildcard interpretation) — the second exists precisely because real names contain [ ] (issue #2).

Get-PSProvider | Select-Object Name, Drives
Get-ChildItem env: | Where-Object Name -like 'PS*'
New-PSDrive -Name Lab -PSProvider FileSystem -Root ~/pslab | Out-Null; Get-ChildItem Lab:\data
Follow-ups
  • Do .NET methods understand PSDrives? No — [IO.File]::ReadAllText('Lab:\x') fails, and relative paths resolve against the process directory, not $PWD. Use Convert-Path / Resolve-Path first (we hit exactly this while writing issue #50).
Red flags

Mixing Set-Location with .NET relative paths in scripts.

Whiteboard: the life of a command line (Q1, Q3, Q4, Q5, Q7)

HostPSReadLine · line Parser → ASTmodes, quoting Q7 Discoveryalias→fn→cmdlet→exe Q3 Bindernamed, positional, pipe Q4 Pipelinebegin/process/end Out-Defaultviews → text Q5 Session state (Q8)scopes: global › script › functionmodule session state (own)dot-source = caller's scoperunspace = separate world Streams (Q6)1 output · 2 error · 3 warning4 verbose · 5 debug · 6 informationWrite-Host → 6 (with host tag)*> redirects all Process boundary (Q12)-File: exit N passes through-Command: 0/1 from $?native: $LASTEXITCODEprofiles load unless -NoProfile
Figure 5-1: draw this in the first minute of a fundamentals interview and hang every answer on it

Answer builder

Choose a question and step through how a strong answer is built: conclusion first, then mechanism, a demo, a production story, the likely follow-up and the red flag you avoid.

Ready.

Mock interview (random question, 2-minute timer)

Scenario 5-1: “works on my machine” three ways

A colleague's report.ps1 works in their terminal. In Task Scheduler it hangs; in CI it exits 1 although the script uses exit 3; on a Linux runner ls | Where-Object Length -gt 1MB returns nothing. Give one root cause per symptom and one standard that prevents all three.

Reference answer points
  • Hang: a prompt (missing mandatory parameter or Read-Host) without -NonInteractive (Hour 1 M1). CI: pwsh -Command flattens exit codes (#5). Linux: ls is the native program (#4).
  • Standard: one launcher line pwsh -NoProfile -NonInteractive -File, full cmdlet names enforced by PSScriptAnalyzer, CI on Windows and Linux, reproduction with Invoke-L9Clean.

Scenario 5-2: explain objects to a Bash team

A team of Bash experts asks why they should not just pwsh -c 'Get-Process' | grep pwsh | awk …. Explain in two minutes with one demo.

Reference answer points
  • Inside PowerShell, data is typed objects — Get-Process | Where-Object CPU -gt 10 | Sort-Object WS needs no parsing and does not break when column widths change.
  • Text appears only at the boundary: Out-Default for humans, ConvertTo-Json/Export-Csv for machines.
  • Demo: Get-Process -Id $PID | Get-Member vs the same via text; mention that formatting is width-dependent, so grepping formatted output is fragile (#1).
or score ≥ 70% on the Quiz

Module 6 · Part B: Tool-making and data (interview Q14–25)

37:00 – 44:00 · advanced functions, pipeline input design, parameter sets, ShouldProcess, output contracts, module structure and publishing, splatting vs Invoke-Expression, data formats, performance, data structures, regex and configuration
7 mindesign → contract → code12 questions★★★★☆
Learning objectives
  • Explain how you build a tool other people can rely on: typed parameters, validation, pipeline input, ShouldProcess, objects out, a module with an explicit export list and a version.
  • Defend data and performance choices with measurements (#20, #22) rather than habits.
  • Use OpsKit as your running example: Get-OpsServer, Test-OpsEndpoint, Invoke-OpsBackup, Invoke-OpsHealthCheck, Invoke-OpsApi.
Prerequisites: Hour 3, Hour 4. Importance:★★★★☆

Scan the questions, mark the ones you are unsure of, click a row to open the model answer.

Q14. Write (on the whiteboard) an advanced function that accepts server names from the pipeline. What makes it “advanced”?Mid
30-second answer

[CmdletBinding()] (or any [Parameter()] attribute) makes a function behave like a cmdlet: common parameters (-Verbose, -ErrorAction, -WhatIf if declared), $PSCmdlet, strict parameter binding. Pipeline input needs ValueFromPipeline/ByPropertyName and a process block, otherwise only the last item is processed.

function Test-OpsEndpoint {
    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('Name')] [ValidateNotNullOrEmpty()] [string[]]$ComputerName,
        [ValidateRange(1, 65535)] [int]$Port = 8080,
        [ValidateRange(1, 60)] [int]$TimeoutSec = 5
    )
    begin   { $sw = [Diagnostics.Stopwatch]::StartNew() }
    process {
        foreach ($c in $ComputerName) {                 # handles both pipeline and -ComputerName a,b
            $ok = Test-Connection $c -TcpPort $Port -TimeoutSeconds $TimeoutSec -Quiet
            [pscustomobject]@{ ComputerName = $c; Port = $Port; Reachable = $ok }
        }
    }
    end     { Write-Verbose "checked in $($sw.Elapsed)" }
}
Follow-ups
  • Why the inner foreach? From the pipeline $ComputerName holds one item per process call; as a parameter it holds the whole array.
  • Why the alias Name? So that Import-Csv servers.csv | Test-OpsEndpoint binds by property name.
Red flags

No process block; Write-Host instead of objects; untyped parameters.

Q15. ValueFromPipeline or ValueFromPipelineByPropertyName — how do you choose? What goes wrong if both accept strings?Senior
30-second answer

ByValue for the primary input type of the command (a path string, a FileInfo, your own object type). ByPropertyName for fields of other commands' objects (ComputerName, Name, Id) so tools compose. If two parameters in the same set accept string by value, every string binds to the first one tried — or a complex object is coerced to a string (ToString()) and lands in the wrong parameter. Typed objects and distinct parameter sets avoid it; Trace-Command ParameterBinding proves it.

Import-Csv ../data/servers.csv | Test-OpsEndpoint          # ByPropertyName via alias Name
'web-01', 'api-01' | Test-OpsEndpoint                         # ByValue
Follow-ups
  • How does Get-Content handle both FileInfo and strings? -Path ByValue (string), -LiteralPath ByPropertyName (alias PSPath).
Red flags

“I make every parameter ValueFromPipeline to be flexible.”

Q16. Design parameters for Get-OpsServer: by name, by environment, or all. How do you prevent impossible combinations?Mid
30-second answer

Parameter sets: each set is a valid combination; DefaultParameterSetName resolves ambiguity; $PSCmdlet.ParameterSetName tells you which one bound. Validation attributes (ValidateSet, ValidatePattern, ValidateScript) and ArgumentCompleter give errors and tab completion before your code runs.

function Get-OpsServer {
    [CmdletBinding(DefaultParameterSetName = 'All')]
    param(
        [Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0)] [SupportsWildcards()] [string[]]$Name,
        [Parameter(Mandatory, ParameterSetName = 'ByEnv')] [ValidateSet('dev', 'staging', 'prod')] [string]$Environment,
        [string]$Path = (Join-Path $HOME 'pslab' 'data' 'servers.csv')
    )
    $all = Import-Csv -LiteralPath $Path
    switch ($PSCmdlet.ParameterSetName) {
        'ByName' { $all | Where-Object { $n = $_.Name; $Name.Where({ $n -like $_ }).Count } }
        'ByEnv'  { $all | Where-Object Env -eq $Environment }
        default  { $all }
    }
}
Follow-ups
  • Error if both are given? “Parameter set cannot be resolved using the specified named parameters.” — before any code runs.
  • Dynamic validation (environments from config)? ArgumentCompleter plus a runtime check, or a class implementing IValidateSetValuesGenerator.
Red flags

Validating combinations with nested ifs in the body.

Q17. How do you implement -WhatIf and -Confirm correctly? What is ConfirmImpact?Mid
30-second answer

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] and wrap every side effect in if ($PSCmdlet.ShouldProcess($target, $action)) { … }. ConfirmImpact is compared with $ConfirmPreference (default High): High-impact operations prompt by default. Pass -WhatIf:$WhatIfPreference to commands from other modules, and guard .NET/REST/native calls yourself — issue #50 shows both failure modes.

if ($PSCmdlet.ShouldProcess($rg.ResourceGroupName, 'Remove resource group')) {
    Remove-AzResourceGroup -Name $rg.ResourceGroupName -Force -WhatIf:$WhatIfPreference
}
Follow-ups
  • Non-interactive automation and ConfirmImpact High? Callers pass -Confirm:$false; with -NonInteractive an unexpected prompt fails instead of hanging.
  • How do you test it? Pester: run with -WhatIf and assert nothing changed (Lab 4-C).
Red flags

Declaring SupportsShouldProcess and assuming that makes the function safe. Do not rely on the analyzer here: PSScriptAnalyzer 1.25.0 did not warn about a function that declared it and called Remove-Item without $PSCmdlet.ShouldProcess() (checked for this lesson) — exactly the pattern that breaks across module boundaries (#50).

Q18. What should a function output? How do you define and test its output contract?Mid
30-second answer

Objects, one per logical result, of a consistent type with stable property names — never formatted text. Declare [OutputType()], give custom objects a type name (PSTypeName = 'OpsKit.HealthResult') for format views, and make sure nothing else leaks into the output ($null =, issue #21). Test type, property names and count for 0/1/many inputs.

[pscustomobject]@{ PSTypeName = 'OpsKit.HealthResult'; Server = $s; Ok = $ok; Ms = $ms }
# Pester 6
$r = @(Invoke-OpsHealthCheck -ComputerName web-01)
$r.Count | Should-Be 1
$r[0].PSObject.TypeNames[0] | Should-Be 'OpsKit.HealthResult'
Follow-ups
  • Classes instead? PowerShell classes give real types but are awkward across module reloads and runspaces; PSCustomObject + type name is the pragmatic default.
Red flags

Mixed output (strings and objects), or return believed to be the only output.

Q19. Walk me through the structure of a production module and how you release it.Senior
30-second answer

Manifest (.psd1: version, GUID, RootModule, RequiredModules, explicit FunctionsToExport, CompatiblePSEditions, PowerShellVersion), root module (.psm1 dot-sourcing Public/ and Private/), format/type files, tests, README/CHANGELOG. Release: CI runs PSScriptAnalyzer and Pester on Windows + Linux, builds (merging files is optional), stamps the SemVer version, signs if required, and Publish-PSResource to a private feed (Azure Artifacts, a NuGet v3 feed or a file share); consumers pin versions.

OpsKit/
  OpsKit.psd1   OpsKit.psm1   Public/*.ps1   Private/*.ps1   OpsKit.Format.ps1xml   tests/*.Tests.ps1
Publish-PSResource -Path ./out/OpsKit -Repository OpsFeed -ApiKey $key
Follow-ups
  • Breaking change? Major version bump, deprecation warnings one release earlier, RequiredModules with versions in consumers.
  • Why not FunctionsToExport = '*'? Issue #41: accidental API and slow discovery.
Red flags

“We copy the .ps1 files to the servers”; no version pinning.

Q20. When do you use splatting? Why is Invoke-Expression almost never the answer for building commands?Junior
30-second answer

Splatting passes a hashtable (named) or array (positional) of parameters with @params: readable long calls, optional parameters added conditionally, and forwarding $PSBoundParameters. To choose the command dynamically use the call operator & $cmd @params. Invoke-Expression re-parses a string as code, so any data inside becomes code — injection (Q49) — and quoting breaks on odd values.

$params = @{ Path = '../data'; Filter = '*.csv'; File = $true }
if ($env:NO_SUCH_FLAG) { $params.Recurse = $true }
(Get-ChildItem @params).Name
$cmd = 'Get-ChildItem'; (& $cmd @params).Count
servers.csv
1
Follow-ups
  • Forwarding parameters? Get-Thing @PSBoundParameters — remove keys the inner command does not have first.
Red flags

Building "Get-ChildItem -Path $p" strings and running them with iex.

Q21. CSV, JSON, CliXml, PSD1 — which do you use for what, and what do you lose with each?Mid
30-second answer

CSV: flat tables for humans/Excel; everything becomes a string (#7, #12), no nesting. JSON: interchange with APIs and other tools; keeps numbers/bools/nesting, watch -Depth (#10), dates become strings, single items unroll (#9). CliXml: PowerShell-to-PowerShell fidelity (type names, nested objects) but deserialized objects (#29); on Windows Export-Clixml protects credentials with DPAPI (user + machine bound) — on Linux/macOS it does not encrypt. PSD1: configuration read safely with Import-PowerShellDataFile (no code execution).

Import-PowerShellDataFile ../data/opskit.config.psd1
Get-Content ../data/inventory.json -Raw | ConvertFrom-Json -AsHashtable
Follow-ups
  • YAML? Not built in; the powershell-yaml module is common — pin it and validate the schema.
Red flags

Dot-sourcing a config .ps1 (code execution); storing secrets with Export-Clixml on Linux believing they are encrypted.

Q22. A script that processes 500,000 log lines takes 20 minutes. How do you make it fast?Senior
30-second answer

Measure first (Measure-Command, Stopwatch per stage). Usual wins: stream instead of loading ([IO.File]::ReadLines, switch -File); filter left; avoid += on arrays (#20) and string += (use StringBuilder or -join); use foreach statements instead of ForEach-Object in hot loops; compile regexes once ([regex]::new(…, 'Compiled')); use hashtables/HashSet for lookups instead of Where-Object in a loop; parallelize only I/O-bound work.

$status = @{}
switch -Regex -File ../data/access.log { '" (\d{3}) ' { $status[$Matches[1]]++ } }
($status.GetEnumerator() | Sort-Object Name | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join ' '
200=463 201=54 301=12 302=17 304=18 400=3 401=6 404=18 500=8 502=4 503=8
Follow-ups
  • Is -Parallel the answer? Not for CPU-light per-line work: runspace overhead dominates (#35).
  • Memory? Get-Content without -ReadCount creates an object per line with provider properties — slow for big files.
Red flags

Optimizing without measuring; “PowerShell is just slow”.

Q23. Hashtable, ordered dictionary, PSCustomObject or class — when do you use which?Junior
30-second answer

Hashtable for lookups and splatting (fast key access, case-insensitive keys, no order, #19). [ordered] when order matters (output, JSON). PSCustomObject for records you output and pipe (properties, formatting, binding by property name). Classes for real types with methods, validation and enums — useful inside modules, less so across runspaces and module reloads.

$byIp = @{}; Import-Csv ../data/servers.csv | ForEach-Object { $byIp[$_.IP] = $_ }
$byIp['10.30.2.51'].Name          # edge-01, O(1) lookup
Follow-ups
  • Case-sensitive keys? [System.Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal).
Red flags

Piping hashtables into Export-Csv (you get Keys/Values/Count columns).

Q24. How do you use regular expressions in PowerShell safely? Parse the status code and IP from an access log line.Mid
30-second answer

-match (sets $Matches for scalars only, #16), -replace/-split (regex, #17/#18), Select-String (line-based, #25), switch -Regex, and [regex] for compiled patterns and all matches. Use named groups, single-quoted patterns, [regex]::Escape() for literals, anchors, and test with the edge cases (line 307's quotes).

$rx = [regex]'^(?<ip>\S+) \S+ \S+ \[[^\]]+\] "(?<req>[^"]*)" (?<st>\d{3}) '
$m = $rx.Match((Get-Content ../data/access.log -TotalCount 1)); $m.Groups['ip'].Value, $m.Groups['st'].Value
Follow-ups
  • Catastrophic backtracking? Avoid nested quantifiers on untrusted input; .NET supports a match timeout ([regex]::new($p, 'None', [timespan]::FromSeconds(1))).
Red flags

Using $Matches outside the if; double-quoted patterns with $.

Q25. How should a tool like OpsKit load configuration? Explain precedence and safety.Senior
30-second answer

Precedence: parameter > environment variable > config file > built-in default. Read files with Import-PowerShellDataFile or ConvertFrom-Json (data, not code), validate the schema (required keys, types, allowed environments), resolve paths relative to the config file, keep secrets out (reference a SecretManagement vault or a managed identity instead), and log the effective configuration without secrets.

function Get-OpsConfig {
    [CmdletBinding()] param([string]$Path = $env:OPSKIT_CONFIG ?? (Join-Path $HOME 'pslab' 'data' 'opskit.config.psd1'))
    $cfg = Import-PowerShellDataFile -LiteralPath $Path
    foreach ($k in 'DefaultEnv', 'Environments') { if (-not $cfg.ContainsKey($k)) { throw "config: missing $k" } }
    if ($env:OPSKIT_LOGLEVEL) { $cfg.LogLevel = $env:OPSKIT_LOGLEVEL }
    $cfg
}
Follow-ups
  • Why not a .ps1 config? It executes code with the caller's rights.
  • $PSDefaultParameterValues? Fine inside a script for its own calls; never as hidden global config (#6).
Red flags

Secrets in the config file in the repository; no validation, so a typo becomes $null (#11).

Anatomy of a tool other people can trust

Input contracttyped, validated params Q14 Q16pipeline: ByValue / ByPropName Q15 BehaviourShouldProcess on side effects Q17errors: terminating when fatal Output contractobjects, one type, no leaks Q18format views, not Format-* Packagingmodule, exports, version Q19private feed, pinning Data choices (Q21 Q23)CSV = strings · JSON = types + depth · CliXml = fidelityhashtable lookups · [ordered] · PSCustomObject records Speed (Q22)measure · stream · filter left · no += · hash lookupsparallel only for I/O-bound work
Figure 6-1: interviewers look for contracts — what goes in, what happens, what comes out, how it ships

Answer builder

Step through strong answers to typical tool-making questions.

Ready.

Mock interview (random question, 2-minute timer)

Scenario 6-1: turn a 400-line script into a module

The team's nightly.ps1 (400 lines, global variables, Write-Host everywhere, copy-pasted to 12 servers) must become a module three teams can use. Outline the steps and what you test first.

Reference answer points
  • Extract functions with typed parameters and object output (Q14, Q18); remove globals (parameters/config, Q25); replace Write-Host with Verbose/Information.
  • Module layout, explicit exports, version 0.x, private feed, pinned consumption (Q19); SupportsShouldProcess on destructive functions (Q17).
  • First tests: characterization tests of current outputs on fixture data; then PSScriptAnalyzer and Pester in CI on Windows + Linux.

Scenario 6-2: the Excel inventory

Operations exports the server inventory from Excel to CSV daily. Your tool must report monitored prod servers by role. Which traps do you plan for?

Reference answer points
  • Strings for booleans and numbers (#7, #12) — convert at import; multi-value fields like "web,api" (#15); encodings and BOM from Excel (#46); culture in numbers/dates (#22, #24); renamed columns (#11) — schema validation; duplicates (web-01 per environment) — key on Name + Env.
or score ≥ 70% on the Quiz

Module 7 · Part B: Robustness, testing and debugging (interview Q26–38)

44:00 – 52:00 · error model, preference scoping, native commands, throw vs Write-Error, cleanup, retries, logging, Pester 6, mocking, PSScriptAnalyzer, debugging tools, StrictMode, cross-platform testing
8 minfail loudly → test → observe13 questions★★★★★
Learning objectives
  • Explain PowerShell's error model precisely (non-terminating, statement-terminating, script-terminating) and design functions that fail loudly.
  • Describe a test strategy with Pester 6 (discovery/run phases, BeforeAll, Mock, Should-*), static analysis and a CI matrix — with real output.
  • Show a debugging toolbox beyond Write-Host: Get-Error, breakpoints, Wait-Debugger, Trace-Command, Set-PSDebug.
Prerequisites: Module 3; Hour 5, Hour 8. Importance:★★★★★

Scan the questions, mark the ones you are unsure of, click a row to open the model answer.

Q26. Terminating vs non-terminating errors: which does try/catch see, and how do you make a cmdlet error catchable?Junior
30-second answer

Non-terminating errors (WriteError) are recorded and the pipeline continues; terminating errors (throw, ThrowTerminatingError, parameter binding failures, .NET exceptions) stop the statement and go to catch/trap. -ErrorAction Stop or $ErrorActionPreference = 'Stop' converts non-terminating errors into terminating ones (issue #26). $_ in catch is the ErrorRecord; $_.Exception the .NET exception.

try { Get-Item ./nope -ErrorAction Stop } catch [System.Management.Automation.ItemNotFoundException] { 'missing' }
Follow-ups
  • Statement- vs script-terminating? A cmdlet's terminating error ends the statement and the script continues with the next one unless caught or EAP is Stop; throw is script-terminating.
  • Where else do errors go? $Error (most recent first), -ErrorVariable.
Red flags

“try/catch catches all errors”; empty catch {} blocks.

Q27. You set $ErrorActionPreference = 'Stop' in your script. Which code is affected and which is not?Senior
30-second answer

Your script scope and child scopes (functions you define, scripts you call with &) see it through dynamic scoping. Functions from script modules do not — they look in their module scope and global scope (issue #27 B, same mechanism as #50). Compiled cmdlets honour the preference of the caller's scope. Dot-sourced files can overwrite it (#27 A). Native commands ignore it unless $PSNativeCommandUseErrorActionPreference is set (#28). Jobs and parallel runspaces start with their own defaults.

Invoke-OpsHealthCheck -ErrorAction Stop       # explicit at the call site crosses the module boundary
Follow-ups
  • How do module authors respect callers' preferences? Advanced functions get -ErrorAction; some modules copy caller preferences explicitly ($PSCmdlet.SessionState.PSVariable.GetValue(…) pattern).
Red flags

“Setting it once at the top makes everything stop on error.”

Q28. How do you handle errors from native tools (az, kubectl, terraform, git) in PowerShell 7.6?Mid
30-second answer

Check $LASTEXITCODE after each call, or set $PSNativeCommandUseErrorActionPreference = $true (7.4+) together with $ErrorActionPreference = 'Stop' so a non-zero exit throws NativeCommandExitException (issue #28, reproduced). Do not treat stderr as failure. Capture structured output (-o json) and convert with ConvertFrom-Json. Wrap tools with special exit codes.

$json = az vm list -o json; if ($LASTEXITCODE) { throw "az failed: $LASTEXITCODE" }
$vms = $json | ConvertFrom-Json
$out = git status --porcelain 2>&1            # stderr lines become ErrorRecords in $out — filter by type
Follow-ups
  • terraform plan -detailed-exitcode returns 2 for changes — how with the preference on? Temporarily set it to $false in a small wrapper and branch on 0/1/2.
Red flags

“try/catch around az is enough”; parsing human-readable tool output.

Q29. throw, Write-Error, $PSCmdlet.WriteError, $PSCmdlet.ThrowTerminatingError — when do you use each in an advanced function?Senior
30-second answer

Per-item failure in a pipeline function (one server of fifty is down): $PSCmdlet.WriteError() or Write-Error — non-terminating, the caller decides with -ErrorAction. The whole call cannot continue (bad config, auth failure): $PSCmdlet.ThrowTerminatingError($record) — a statement-terminating error that reports your function as the source, honours the caller's handling and keeps a clean error record. throw is fine in scripts and private helpers; in public functions it produces script-terminating errors that point into your internals.

$err = [System.Management.Automation.ErrorRecord]::new(
    [System.IO.FileNotFoundException]::new("config not found: $Path"), 'OpsKit.ConfigMissing',
    [System.Management.Automation.ErrorCategory]::ObjectNotFound, $Path)
$PSCmdlet.ThrowTerminatingError($err)
Follow-ups
  • Why a FullyQualifiedErrorId? Tests and callers can match on it ($_.FullyQualifiedErrorId -like 'OpsKit.ConfigMissing*') instead of on message text.
Red flags

Returning $false or error strings instead of errors.

Q30. How do you guarantee cleanup (temp files, locks, sessions) even on errors and Ctrl+C?Mid
30-second answer

try { … } finally { … }: the finally block runs on success, on terminating errors and when the pipeline is stopped (Ctrl+C, Stop-Job, a downstream Select-Object -First). Keep finally blocks short and non-failing. For pipeline functions, the clean block (7.3+) runs once at the end even when the pipeline is stopped.

$tmp = New-TemporaryFile
$session = New-PSSession web-01
try { … }
finally {
    Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue
    if ($session) { Remove-PSSession $session }
}
Follow-ups
  • Process killed (OOM, Stop-Process -Force)? Nothing runs; design for it: unique temp names, lock files with stale-lock detection, idempotent re-runs.
  • trap? Older, scope-wide; prefer try/catch.
Red flags

Cleanup code only at the end of the happy path.

Q31. Implement retries for a REST call. What makes a retry strategy safe?Senior
30-second answer

Retry only transient failures (timeouts, connection errors, 408/429/5xx), with exponential backoff + jitter and a cap on attempts and total time; honour Retry-After; make the operation idempotent before retrying writes; log each attempt. Issue #49 shows the real run — and a bug we hit: [math]::Min(30, 0.5) returns 0 because of overload selection and banker's rounding.

$delay = [math]::Min(30.0, $base * [math]::Pow(2, $attempt - 1)) + (Get-Random -Minimum 0.0 -Maximum 0.25)
Follow-ups
  • Built-in -MaximumRetryCount? Fixed interval, retries 4xx as well — fine for simple reads only.
  • Circuit breaker? Stop calling after N consecutive failures across items, fail the job fast.
Red flags

while ($true) { try { …; break } catch { Start-Sleep 1 } }.

Q32. What does good logging look like for a PowerShell job running unattended?Mid
30-second answer

Structured (one JSON object per event: time UTC, level, run id, component, message, key fields) written by one logging function; diagnostics on Verbose/Information streams; errors with $_.ScriptStackTrace and FullyQualifiedErrorId; a summary record at the end (counts, duration, exit code); no secrets (#44). Ship to the platform's log store; keep transcripts as a fallback only.

function Write-OpsLog([ValidateSet('INFO','WARN','ERROR')]$Level, [string]$Message, [hashtable]$Data = @{}) {
    $o = [ordered]@{ ts = [datetime]::UtcNow.ToString('o'); level = $Level; run = $script:RunId; msg = $Message } + $Data
    ($o | ConvertTo-Json -Compress -Depth 5) | Add-Content -LiteralPath $script:LogPath
}
Follow-ups
  • Script block logging? Event 4104, enabled by policy, logs executed code — useful for security, and another place secrets can appear.
Red flags

Write-Host with colours as the only log; logging full request headers.

Q33. How does Pester 6 work? Show a test for a module function.Mid
30-second answer

Since Pester 5 a run has two phases: Discovery (runs the file top-level and the Describe/Context/It blocks' declarations to build the test tree; code outside BeforeAll/It runs then) and Run. Put setup in BeforeAll/BeforeEach. Pester 6 adds the Should-* assertion functions (Should-Be, Should-Throw, Should-Invoke…) next to the legacy Should -Be syntax, and requires a supported PowerShell version. Make sure the right Pester is loaded (#39).

# ./pester/OpsApi.Tests.ps1
BeforeAll { Import-Module "$PSScriptRoot/OpsApi.psm1" -Force }
Describe 'Invoke-OpsApi' {
    BeforeEach { Mock Invoke-RestMethod -ModuleName OpsApi -MockWith { @{ status = 'ok' } } }
    It 'returns one typed result' {
        $r = @(Invoke-OpsApi -Path 'healthz')
        $r.Count | Should-Be 1
        $r[0].PSObject.TypeNames[0] | Should-Be 'OpsKit.ApiResult'
    }
    It 'sets a timeout on every call' {
        Invoke-OpsApi -Path 'healthz' | Out-Null
        Should-Invoke Invoke-RestMethod -ModuleName OpsApi -Times 1 -Exactly -ParameterFilter { $TimeoutSec -eq 30 }
    }
    It 'fails loudly when the API fails' {
        Mock Invoke-RestMethod -ModuleName OpsApi -MockWith { throw 'HTTP 503' }
        { Invoke-OpsApi -Path 'healthz' } | Should-Throw
    }
}
Import-Module ./modules/Pester -MinimumVersion 6.0
Invoke-Pester -Path ./pester/OpsApi.Tests.ps1 -Output Detailed
Pester v6.2.0

Running tests from 1 files.

Running tests from 'C:\Users\labadmin\pslab\lab9\pester\OpsApi.Tests.ps1'
Describing Invoke-OpsApi
  [+] returns one typed result 445ms
  [+] sets a timeout on every call 133ms
  [+] fails loudly when the API fails 97ms
Tests completed in 1.56s
Tests Passed: 3, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Follow-ups
  • Why did my variable defined at file level not exist in the It block? It ran during discovery, not run — move it into BeforeAll.
  • Data-driven tests? It … -ForEach @(@{ n = 0 }, @{ n = 1 }).
Red flags

Tests that call real APIs or production; Pester 3 syntax in a 6.x shop.

Q34. How do you mock a dependency that is called inside your module? What is InModuleScope for?Senior
30-second answer

Mock Cmd -ModuleName OpsKit places the mock in the module's session state, which is where the module's functions resolve commands (the same boundary as #27/#50) — a mock in the test scope alone would not be seen. InModuleScope OpsKit { … } runs test code inside the module to test private functions or read module variables; use it sparingly — test public behaviour first. Verify calls with Should-Invoke … -ParameterFilter (Q33 output).

Follow-ups
  • Mocking .NET calls? You cannot mock [IO.File]::ReadAllText; wrap it in a small private function and mock that, or use $TestDrive with real files.
  • Mocking native tools? Wrap az/kubectl in functions (they also centralize exit-code checks, Q28).
Red flags

“Mocks didn't work so I removed the test”; mocking the function under test.

Q35. What does PSScriptAnalyzer catch, and how do you gate CI on it?Junior
30-second answer

Static rules over the AST: aliases, Write-Host, plain-text passwords, null comparison order, missing $using:, unapproved verbs, ShouldProcess usage, BOM for non-ASCII files, formatting. Run Invoke-ScriptAnalyzer -Recurse -Settings ./PSScriptAnalyzerSettings.psd1 in CI, fail on Error/Warning, suppress individual findings in code with [Diagnostics.CodeAnalysis.SuppressMessageAttribute()] and a justification.

Save-PSResource PSScriptAnalyzer -Path ./modules -TrustRepository -Quiet
Import-Module ./modules/PSScriptAnalyzer
Set-Content ./bad.ps1 -Value @'
function Remove-Temp {
    [CmdletBinding(SupportsShouldProcess)]
    param($Path, $Password)
    ls $Path | ? { $_.Name -like '*.tmp' } | rm
    if ($Path -eq $null) { Write-Host 'no path' }
    1..3 | ForEach-Object -Parallel { "$Path/$_" }
}
'@
"PSScriptAnalyzer $((Get-Module PSScriptAnalyzer).Version)"
Invoke-ScriptAnalyzer ./bad.ps1 | Sort-Object Line, RuleName | Format-Table Line, Severity, RuleName -AutoSize
PSScriptAnalyzer 1.25.0

Line Severity RuleName
---- -------- --------
   3  Warning PSAvoidUsingPlainTextForPassword
   3  Warning PSReviewUnusedParameter
   4  Warning PSAvoidUsingCmdletAliases
   4  Warning PSAvoidUsingCmdletAliases
   4  Warning PSAvoidUsingCmdletAliases
   5  Warning PSAvoidUsingWriteHost
   5  Warning PSPossibleIncorrectComparisonWithNull
   6  Warning PSUseUsingScopeModifierInNewRunspaces
Follow-ups
  • What does it miss? Logic and runtime issues: #7 CSV booleans, #9 unrolling, #33 races, #50 WhatIf across modules — that is what tests are for. Note that line 2 (SupportsShouldProcess without calling ShouldProcess) produced no finding.
Red flags

Suppressing rules globally to make CI green.

Q36. A script fails only in production. Which debugging tools do you use, in which order?Mid
30-second answer

1) Get-Error (7+) on the failing record: exception chain, ScriptStackTrace, invocation info. 2) Reproduce in a clean process (pwsh -NoProfile, same account/edition, Module 0's Invoke-L9Clean). 3) Increase observability: -Verbose, Trace-Command for binding, Set-PSDebug -Trace 1 for line tracing (careful with secrets). 4) Interactive: breakpoints in VS Code or Set-PSBreakpoint -Script x.ps1 -Line 42 / -Variable; Wait-Debugger inside a job or remote session and attach with Debug-Job / Enter-PSHostProcess + Debug-Runspace.

$Error[0] | Get-Error
Set-PSBreakpoint -Script ./job.ps1 -Variable servers -Mode Write
Get-Job | Where-Object State -eq 'AtBreakpoint' | Debug-Job
Follow-ups
  • Remote/production host where you cannot attach? Structured logs with enough context (Q32) and a feature flag for verbose logging.
Red flags

Only Write-Host "here 1"; editing the production script to debug.

Q37. What does Set-StrictMode -Version Latest catch? Would you enable it in a module?Mid
30-second answer

Uninitialized variables, references to non-existent properties (issue #11), out-of-range array indexes, function calls with method syntax (f(1,2)), and — verified on 7.6.10 — even .Count on $null or a scalar. Yes, in module and script files (it is scoped to the file/scope where you set it), with tests, because it turns silent $nulls into errors. Watch for code that relies on optional properties: test with $o.PSObject.Properties[$name].

Set-StrictMode -Version Latest
if ($o.PSObject.Properties['Port']) { $o.Port } else { 8080 }
Follow-ups
  • Why “Latest” can be risky? A new PowerShell version can add checks; pin a version (-Version 3.0) if you need stability.
Red flags

Enabling it globally in a profile (it changes behaviour of everything you run interactively).

Q38. Your module claims to support Windows, Linux and both editions. How do you prove it?Senior
30-second answer

A CI matrix (windows-latest, ubuntu-latest, macOS if relevant) × (pwsh 7.6 LTS, plus 5.1 on Windows if CompatiblePSEditions includes Desktop), the same Pester suite and PSScriptAnalyzer settings everywhere, fixtures with odd names, non-ASCII and both line endings, and platform checks in code via $IsWindows/$IsLinux rather than assumptions. Use Join-Path, [IO.Path]::PathSeparator, avoid aliases (#4), case-sensitive file names on Linux.

strategy: { matrix: { os: [windows-latest, ubuntu-latest] } }
- shell: pwsh
  run: ./build.ps1 -Task Test        # bootstrap pins Pester 6 + PSScriptAnalyzer (Lab 4-A)
Follow-ups
  • Typical Linux-only failures? Case-sensitive paths, missing Windows-only cmdlets (Get-CimInstance without CIM), hidden files (.name), line endings in scripts with shebangs (#47).
Red flags

“It works on my Windows laptop, Linux is the same.”

Quality gates for a PowerShell module

Bootstrappinned Pester/PSSA #39 Static analysisPSScriptAnalyzer Q35 Unit testsPester 6 + mocks Q33 Q34 MatrixWindows · Linux · editions Q38 Releaseversion · sign · publish Q19 At run time (production)EAP Stop + native preference (Q26–Q28) · ThrowTerminatingError (Q29) · finally/clean (Q30) · retries with backoff (Q31)structured logs without secrets (Q32) · StrictMode (Q37) · Get-Error / breakpoints / Wait-Debugger (Q36)
Figure 7-1: what you can prove before release, and what must handle failure after it

Answer builder

Step through strong answers to typical robustness questions.

Ready.

Mock interview (random question, 2-minute timer)

Scenario 7-1: quality gates for an 800-line deployment script without tests

You inherit deploy.ps1: no tests, used weekly for production. What do you do in the first week, without a rewrite?

Reference answer points
  • Run PSScriptAnalyzer and fix the high-value findings (aliases, null comparisons, plain-text passwords, missing $using:).
  • Add $ErrorActionPreference = 'Stop', $PSNativeCommandUseErrorActionPreference = $true, Set-StrictMode in a branch and run it in a test environment; fix what surfaces.
  • Characterization tests around the riskiest functions with mocks for cloud calls; a -WhatIf mode that is actually propagated (#50); CI with the launcher line pwsh -NoProfile -NonInteractive -File.

Scenario 7-2: “deployment succeeded but the old version is running”

The pipeline is green, the app runs the old build — intermittently. How do you investigate?

Reference answer points
  • Look for swallowed errors: non-terminating errors in remote/parallel parts (#26, #34), native tools without exit-code checks (#28), empty catch.
  • Look for races: parallel copies, file locks (#23), a service restart that is not awaited; add verification (version endpoint) as the last step and fail if it does not match.

Scenario 7-3: Ctrl+C leaves half-written output

Operators stop a long export with Ctrl+C; the next run reads a truncated file and imports garbage.

Reference answer points
  • Write to a temp file and rename on success (#23); delete the temp in finally (Q30); validate input files (row counts, schema) before importing (#11).
or score ≥ 70% on the Quiz

Module 8 · Part B: Real-world scenarios and code review (interview Q39–50)

52:00 – 60:00 · fan-out health checks, six code-review snippets (formatting and output, error handling, secrets, parallel state, REST paging, injection), double hop, Azure automation, the 2 a.m. silent failure, 5.1 → 7.6 migration and a module release pipeline
8 mindestructive → silent → security → concurrency → maintainability12 questions★★★★★
Learning objectives
  • Structure scenario answers: clarify requirements and constraints, design, failure handling, security, how you would verify it.
  • Review code in a fixed order — destructive actions → silent failures → security → concurrency → maintainability — and propose a corrected version.
  • Connect every finding to a Part A issue number: that is your “production experience”.
Prerequisites: Modules 1–7. Importance:★★★★★ (senior interviews are decided here)

Six of these are code-review questions (Q40, Q41, Q42, Q45, Q47, Q49). Click a row to open the model answer.

Q39. Design a health check of 500 HTTP endpoints that must finish in under 2 minutes and report clearly which ones failed.Senior
30-second answer

I/O-bound → ForEach-Object -Parallel with an explicit -ThrottleLimit (e.g. 32; default 5 would take far too long, #35), a per-request timeout (#38), results returned as objects (no shared state, #33), a summary that compares input and output sets (missing results = failures too), and a non-zero exit code if anything failed. 500 × 5 s worst case / 32 ≈ 80 s.

$results = $endpoints | ForEach-Object -ThrottleLimit 32 -Parallel {
    $sw = [Diagnostics.Stopwatch]::StartNew()
    try {
        $null = Invoke-WebRequest $_ -TimeoutSec 5 -SkipHttpErrorCheck -StatusCodeVariable sc
        [pscustomobject]@{ Url = $_; Status = $sc; Ms = $sw.ElapsedMilliseconds; Ok = $sc -lt 400 }
    } catch { [pscustomobject]@{ Url = $_; Status = 0; Ms = $sw.ElapsedMilliseconds; Ok = $false; Error = $_.Exception.Message } }
}
$failed = @($results | Where-Object { -not $_.Ok })
$results | ConvertTo-Json -Depth 3 | Set-Content ./health.json
if ($failed.Count -or $results.Count -ne $endpoints.Count) { exit 1 }
Follow-ups
  • Hosts behind one load balancer? Throttle per target and respect rate limits.
  • Windows servers instead of URLs? Invoke-Command -ComputerName $list -ThrottleLimit 64 -AsJob fans out on the remote side; return small objects (#29).
Red flags

A sequential loop; $using:results.Add(); no timeouts.

Q40. Code review: a daily report script. Find the problems.Mid
$report = @()
foreach ($s in Import-Csv servers.csv) {
    if ($s.Monitored) {
        $report += Get-CimInstance Win32_LogicalDisk -ComputerName $s.Name |
            Format-Table DeviceID, FreeSpace
    }
}
$report | Out-File \\share\reports\disk.txt
Write-Host "Report done for $report.Count servers"
Model answer (in review order)
  • Silent wrong data: $s.Monitored is a string → every server is included (#7). Relative servers.csv depends on the current folder (use $PSScriptRoot).
  • Output contract: Format-Table inside the loop → format records in the report (#1); Write-Host with $report.Count in a string prints the array (#3).
  • Failures invisible: unreachable servers produce non-terminating errors and are simply missing; no exit code.
  • Performance: += (#20); sequential CIM calls — Get-CimInstance -ComputerName $list fans out.
  • Encoding/consumers: a text table on a share; prefer CSV/JSON with explicit encoding.
$servers = Import-Csv (Join-Path $PSScriptRoot 'servers.csv') | Where-Object Monitored -eq 'true'
$disks = Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ComputerName $servers.Name -ErrorVariable cimErr |
    Select-Object PSComputerName, DeviceID, @{ n = 'FreeGB'; e = { [math]::Round($_.FreeSpace / 1GB, 1) } }
$disks | Export-Csv \\share\reports\disk.csv -NoTypeInformation -Encoding utf8BOM
Write-Information "Report: $(@($disks.PSComputerName | Sort-Object -Unique).Count) of $($servers.Count) servers" -InformationAction Continue
if ($cimErr) { Write-Warning "$($cimErr.Count) server(s) failed"; exit 1 }
Red flags

Only commenting on style (aliases, brace placement) while missing #7 and #1.

Q41. Code review: “the cleanup prints ‘cleaned’ even when the path does not exist”.Junior
$ErrorActionPreference = 'Continue'
function Remove-OldLogs([string]$Path) {
    try {
        Get-ChildItem $Path -Filter *.log | Remove-Item
        Write-Output "cleaned $Path"
    } catch {
        Write-Output "failed: $_"
    }
}
Remove-OldLogs ./does-not-exist
Get-ChildItem: 
Line |
   4 |          Get-ChildItem $Path -Filter *.log | Remove-Item
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:\Users\labadmin\pslab\lab9\does-not-exist' because it does not exist.
cleaned ./does-not-exist
Model answer
  • Get-ChildItem's error is non-terminating, so catch never runs and “cleaned” is printed (#26).
  • -Path with wildcards (#2); no -WhatIf support for a deleting function (Q17); no filter on age although the name says “old”; output is a string, not an object.
function Remove-OldLog {
    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory)][string]$Path, [int]$OlderThanDays = 14)
    $cutoff = (Get-Date).AddDays(-$OlderThanDays)
    $files = Get-ChildItem -LiteralPath $Path -Filter *.log -File -ErrorAction Stop | Where-Object LastWriteTime -lt $cutoff
    foreach ($f in $files) { if ($PSCmdlet.ShouldProcess($f.FullName, 'Delete')) { Remove-Item -LiteralPath $f.FullName -ErrorAction Stop } }
    [pscustomobject]@{ Path = $Path; Removed = @($files).Count; WhatIf = [bool]$WhatIfPreference }
}
Q42. Code review: credentials in a provisioning script.Mid
$user = 'svc-deploy'
$pass = ConvertTo-SecureString 'Winter2026!' -AsPlainText -Force
$cred = [pscredential]::new($user, $pass)
Start-Transcript C:\logs\provision.log
Write-Verbose "Using $user / Winter2026!" -Verbose
$cred | Export-Clixml ./cred.xml          # reused by the Linux runner later
Invoke-RestMethod "https://api.example.com/deploy?token=$env:API_TOKEN" -Method Post
Model answer
  • Password in source control (and in the transcript via the verbose message, #44) — rotate it now.
  • -AsPlainText from a literal gives no protection; PSScriptAnalyzer flags PSAvoidUsingConvertToSecureStringWithPlainText.
  • Export-Clixml encrypts with DPAPI only on Windows and only for the same user and machine; on Linux the file holds the secret in plain text.
  • Token in the query string ends up in proxy logs, error messages and the transcript; use an Authorization header (-Authentication Bearer -Token $secureToken).
  • Fix: SecretManagement vault or the platform's secret store / managed identity; no transcripts of secret-handling sessions; mask in CI.
$cred  = Get-Secret -Name DeployCredential -Vault OpsVault          # PSCredential
$token = Get-Secret -Name ApiToken -Vault OpsVault                  # SecureString
Invoke-RestMethod https://api.example.com/deploy -Method Post -Authentication Bearer -Token $token
Q43. Invoke-Command to web-01 cannot read \\fs01\packages. Explain and give three solutions with their trade-offs.Senior
30-second answer

Kerberos double hop (#31): the remote session has no delegable credential. Solutions: avoid the hop (copy the package to the target with Copy-Item -ToSession, or have the target pull with its own computer account rights); resource-based constrained delegation (configured on fs01's computer object to trust web-01 — scoped, no credential exposure); explicit credentials inside the session from a vault (simple, but a credential travels and must be protected). CredSSP works but hands a reusable credential to the target — avoid on servers that might be compromised. JEA with a gMSA run-as account suits delegated admin.

$s = New-PSSession web-01
Copy-Item ./packages/app-1.4.2.zip -Destination C:\deploy\ -ToSession $s
Invoke-Command -Session $s { Expand-Archive C:\deploy\app-1.4.2.zip C:\app -Force }
Follow-ups
  • Deserialized results? Do the work remotely, return small objects (#29).
  • Non-domain or Linux targets? SSH remoting with keys (#37).
Red flags

“Enable CredSSP everywhere” or “add the share to Everyone”.

Q44. Write an Azure automation that deletes expired temporary resource groups every night. How do you make it safe?Senior
30-second answer

Identity: a managed identity (or workload identity federation from CI) with a custom role scoped to the target subscription(s). Context: Connect-AzAccount -Identity, explicit Set-AzContext -Subscription per subscription, context autosave off (#43). Selection: tags (expires < today, owner present) plus a name pattern allow-list; never by absence of a tag. Safety: -WhatIf mode for PRs (propagated, #50), resource locks respected, a maximum number of deletions per run (circuit breaker), structured logs and a report. Robustness: retries for throttling (429) with backoff (#49), -AsJob or parallelism with throttling for many groups.

$today = (Get-Date).ToUniversalTime().Date
$expired = Get-AzResourceGroup -Tag @{ purpose = 'temp' } |
    Where-Object { $_.Tags.expires -and [datetime]::ParseExact($_.Tags.expires, 'yyyy-MM-dd', $null) -lt $today }
if ($expired.Count -gt 20) { throw "refusing to delete $($expired.Count) groups in one run" }
$expired | ForEach-Object { Remove-AzResourceGroup -Name $_.ResourceGroupName -Force -WhatIf:$WhatIfPreference -AsJob }
Red flags

A user account with Owner on the tenant; relying on the saved context; no dry-run.

Q45. Code review: a parallel inventory collector.Mid
$inventory = [System.Collections.Generic.List[object]]::new()
$errors = 0
function Get-Info($name) { Invoke-RestMethod "http://$name:8080/info" }
$servers | ForEach-Object -Parallel {
    try { $using:inventory.Add((Get-Info $_)) }
    catch { $errors++ }
}
"collected $($inventory.Count), errors $errors"
Model answer
  • Get-Info does not exist in the parallel runspaces (#32) — every item fails.
  • $errors++ modifies a runspace-local variable; the caller prints 0 (#33). List[T].Add from several threads is a race (#33).
  • "http://$name:8080/info": $name:8080 is parsed as a drive-qualified variable (like $env:PATH), which is empty and swallows the port — verified below. Use ${name} or $($name).
$name = 'web-01'
"http://$name:8080/info"
http:///info
  • No timeout (#38), default throttle 5 (#35), errors swallowed.
$results = $servers | ForEach-Object -ThrottleLimit 32 -Parallel {
    try   { [pscustomobject]@{ Name = $_; Ok = $true;  Info = Invoke-RestMethod "http://${_}:8080/info" -TimeoutSec 5 } }
    catch { [pscustomobject]@{ Name = $_; Ok = $false; Info = $_.Exception.Message } }
}
$bad = @($results | Where-Object { -not $_.Ok }); "collected $(@($results).Count - $bad.Count), errors $($bad.Count)"
Q46. A scheduled PowerShell task “ran successfully” at 2 a.m. but did nothing. How do you triage?Mid
30-second answer

Follow the triage tree (Module 4): 1) What exactly ran — action line, account, start folder (pwsh -NoProfile -NonInteractive -File? relative paths? #5, #6). 2) Exit code reported vs real (-Command flattening; errors that were non-terminating so the script exited 0, #26). 3) Environment of that account: PSModulePath and module versions (#39–#42), network/proxy, credentials, mapped drives (not available to services). 4) Data: empty input that made loops run zero times (#9, #11). Reproduce as that account with the same command line, add a run log with counts and a non-zero exit when count is unexpectedly 0.

Get-ScheduledTaskInfo -TaskName OpsNightly | Select-Object LastRunTime, LastTaskResult
(Get-ScheduledTask OpsNightly).Actions | Select-Object Execute, Arguments, WorkingDirectory
Red flags

“Rerun it manually and see” — as yourself, with your profile and modules.

Q47. Code review: fetching all items from a paged API.Senior
$uri = "https://api.example.com/v1/servers?top=100"
$all = @()
while ($uri) {
    $page = Invoke-RestMethod $uri -Headers @{ Authorization = "Bearer $token" }
    $all += $page.value
    $uri = $page.nextLink
}
$all | ConvertTo-Json | Set-Content servers.json
Model answer
  • No timeout and no retry on 429/5xx (#38, #49); one transient error loses all progress; no limit on pages (a buggy nextLink loops forever).
  • += per page (#20); ConvertTo-Json default depth (#10); single item → not an array (#9).
  • Errors: the API's error body is lost (#48). $token as a plain string in a header (prefer -Authentication Bearer -Token with a SecureString).
  • Alternatives: Invoke-RestMethod -FollowRelLink for APIs using Link headers; Az/Graph SDK cmdlets handle paging for you.
$items = [System.Collections.Generic.List[object]]::new(); $pages = 0
while ($uri -and $pages++ -lt 1000) {
    $page = Invoke-OpsApi -Uri $uri -Method Get        # OpsKit wrapper: timeout, backoff, ErrorDetails logging
    $items.AddRange(@($page.value)); $uri = $page.nextLink
}
ConvertTo-Json -InputObject $items -Depth 10 | Set-Content ./servers.json -Encoding utf8
Q48. You must migrate 200 Windows PowerShell 5.1 scripts to PowerShell 7.6. What is your plan?Senior
30-second answer

Inventory and risk-rank (who runs what, where, how often). Static scan: PSScriptAnalyzer with the PSUseCompatibleCommands, PSUseCompatibleSyntax and PSUseCompatibleTypes rules targeting 7.6, plus searches for *-WmiObject, -Encoding Byte, Out-File/> consumers, curl/wget aliases, ConvertTo-Json depth assumptions, [System.Web] and other .NET Framework-only APIs. Modules: check availability for Core; compatibility session only as a bridge (#40). Behaviour diffs: encoding (#46), native argument passing, JSON/number formatting. Run both editions side by side in CI with the same tests, switch the launcher to pwsh script by script, keep 5.1 available for rollback.

Follow-ups
  • Which issues show up most? Encoding of output files consumed by other systems, WMI cmdlets, modules installed only for 5.1 (#40), scheduled tasks still calling powershell.exe.
Red flags

“Just change powershell.exe to pwsh in all tasks over a weekend.”

Q49. Code review: a “flexible” file lookup that builds a command string.Mid
param([string]$Name)
Invoke-Expression "Get-Item ../data/$Name"
Model answer

Code injection: the value is re-parsed as PowerShell, so ;, $( ) or a second statement in $Name runs with the caller's rights. Demonstration with a harmless payload:

$name = "servers.csv; 'INJECTED: a second command ran'"
Invoke-Expression "Get-Item ../data/$name" | Select-Object -Last 1
Get-Item -LiteralPath "../data/$name" -ErrorAction SilentlyContinue; "safe: exists=$?"
INJECTED: a second command ran
safe: exists=False
  • Fix: call the command directly with data as an argument (Get-Item -LiteralPath (Join-Path $base $Name)), validate input ([ValidatePattern('^[\w.-]+$')]), and check the resolved path stays under the base folder (path traversal ../../).
  • PSScriptAnalyzer: PSAvoidUsingInvokeExpression. The same applies to building pwsh -Command "…$input…" strings and [scriptblock]::Create() with user data.
Q50. Design the release pipeline for OpsKit v1.x used by five teams.Senior
30-second answer

Trunk-based with PRs. PR pipeline: bootstrap pinned tools (#39), PSScriptAnalyzer with repo settings, Pester 6 unit tests with mocks on Windows + Linux, code coverage threshold, -WhatIf tests for destructive commands (#50), manifest checks (exports equal Public/, #41; version bumped). Release pipeline on tag: build artifact, sign scripts if policy requires (Authenticode with a certificate from a key vault/HSM), generate CHANGELOG, Publish-PSResource to a private feed, smoke test by installing from the feed in a clean container. Consumers pin RequiredModules versions and upgrade via PRs (Dependabot-style). Semantic versioning, deprecation warnings before breaking changes, support for the current LTS only (7.6).

Publish-PSResource -Path ./out/OpsKit -Repository OpsFeed -ApiKey (Get-Secret OpsFeedKey -AsPlainText)
Install-PSResource OpsKit -Version '[1.0.0, 2.0.0)' -Repository OpsFeed -Scope CurrentUser
Follow-ups
  • Hotfix? Branch from the tag, patch version, same gates.
  • How do you know teams are on supported versions? Telemetry-free option: a startup check in the module that warns when a newer major exists on the feed.
Red flags

Manual copying to servers; no tests on Linux although teams run it there; publishing from a laptop.

Code-review order and where each Part A issue fits

1 Destructivewrong target #2 #43WhatIf lost #50same-file rewrite #23CSV “false” #7 2 Silent failurenon-terminating #26native exit #28exit code #5 · jobs #34missing prop #11 3 Securityinjection Q49secrets #44 Q42TrustedHosts #37policy myths #45 4 Concurrency$using: #30functions #32races #33timeouts #38 5 MaintainabilityFormat-* #1aliases #4+= #20 · output #21exports #41
Figure 8-1: say the most dangerous finding first; style comments last

Answer builder

Step through a strong answer to a scenario or code-review question.

Ready.

Mock interview (random question, 2-minute timer)

Scenario 8-1: post-mortem of an accidental deletion

A cleanup run with -WhatIf during a change review deleted 40 resource groups in a shared subscription. Write the five “contributing factors” and the corrective actions.

Reference answer points
  • WhatIf not propagated into a module function (#50); implicit Az context (#43); selection by missing tag; no deletion cap; identity with too broad RBAC.
  • Actions: propagate and test WhatIf (Pester), mandatory subscription parameter, allow-list selection, cap + circuit breaker, scoped managed identity, locks on shared groups, alerts on bulk deletions.

Scenario 8-2: consolidate 30 scattered scripts

Thirty team scripts duplicate logging, retries and API calls. Propose the target structure.

Reference answer points
  • An OpsKit-style module with Invoke-OpsApi (timeouts, backoff, error details), Write-OpsLog, config loader; scripts become thin entry points (param → module calls → exit code). Version, tests and private feed (Q19, Q50).

Scenario 8-3: timed live coding

“In 10 minutes: from access.log, return the 3 paths with the most 5xx responses as objects and exit 1 if any path has more than 10.”

Reference answer points (verified on the dataset)
$counts = @{}
switch -Regex -File ../data/access.log {
    '"[A-Z]+ (?<path>\S+) HTTP/[\d.]+" (?<st>5\d\d) ' { $counts[$Matches.path]++ }
}
$top = $counts.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 3 |
    ForEach-Object { [pscustomobject]@{ Path = $_.Key; Errors5xx = $_.Value } }
$top
$exit = if (@($top | Where-Object Errors5xx -gt 10).Count) { 1 } else { 0 }
"exit code would be: $exit"
Path        Errors5xx
----        ---------
/api/orders        20
exit code would be: 1

All 20 5xx responses are on /api/orders (dataset facts), so the threshold is exceeded and the exit code is 1. Mention streaming (switch -File), numeric conversion, and object output.

or score ≥ 70% on the Quiz

Problem cheat sheet + interview flash cards

50 rows “symptom → first command → fix”, 50 flash cards with the one-line key point of each answer, and eight command cards for triage
PowerShell 7.6Filterable · printable

A · 50 production issues

B · 50 interview flash cards

Triage command cards

1. What is this object?

$x | Get-Member
$x.GetType().FullName; $x.PSObject.TypeNames
@($x).Count                       # 0 / 1 / many (#9)
$x | ConvertTo-Json -Depth 5      # see everything

2. Reproduce like CI

pwsh -NoProfile -NonInteractive -File ./job.ps1; $LASTEXITCODE
$PSVersionTable; whoami; $Host.Name
$env:PSModulePath -split [IO.Path]::PathSeparator
Get-Module Name -ListAvailable | Select Name, Version, ModuleBase

3. Paths and names

Get-Content -LiteralPath $f              # [ ] in names (#2)
Get-Command name -All                     # alias/function/cmdlet/exe (#4)
Join-Path $PSScriptRoot 'data'            # not $PWD
Convert-Path ./x                          # before .NET calls

4. Errors

-ErrorAction Stop                         # make it catchable (#26)
$Error[0] | Get-Error
$PSNativeCommandUseErrorActionPreference = $true   # (#28)
Receive-Job $j -Wait -ErrorVariable je    # (#34)

5. Parallel and remote

ForEach-Object -Parallel { $using:x } -ThrottleLimit 16
$r = $items | ForEach-Object -Parallel { … }   # return, don't share (#33)
Start-ThreadJob { … }                     # not Start-Job (#36)
Invoke-Command -Session $s { … }          # Deserialized.* back (#29)

6. Text and data

Where-Object Monitored -eq 'true'         # CSV strings (#7)
Sort-Object { [int]$_.Conns }             # (#12)
[regex]::Escape($s); $s.Replace(a, b)     # (#17)
ConvertTo-Json -InputObject @($x) -Depth 10   # (#9 #10)

7. Bytes

Format-Hex ./f.txt | Select-Object -First 2
Set-Content -Encoding utf8BOM             # for 5.1 readers (#46)
$raw -split '\r?\n'                       # CRLF safe (#47)
[cultureinfo]::InvariantCulture           # (#22 #24)

8. Safe change

[CmdletBinding(SupportsShouldProcess)]
if ($PSCmdlet.ShouldProcess($t, 'Delete')) { … }
Other-Cmd -WhatIf:$WhatIfPreference       # (#50)
Set-AzContext -Subscription $Id           # (#43)

Comprehensive exercises + mock interview + final quiz

Find eight faults in one nightly job, fix them and prove it with a real run; then a 10-question mock interview drawn from all 50, an open-ended self-check and the 12-question final quiz
about 30 minLocal onlyIntegrates M1–M8

I. Comprehensive fault drill: the nightly inventory job

The job below is supposed to export the monitored servers of one environment to CSV and JSON, run a parallel check per server, print a summary and exit 3 when any check did not know its environment. Save it as ~/pslab/lab9/nightly-broken.ps1, run it the way the scheduler does, and list every fault before opening the answers.

The broken job
param($Env = 'prod')
$servers = Import-Csv ../data/servers.csv | ? { $_.Monitored -and $_.Env -eq $Env }
$report = @()
foreach ($s in $servers) { $report += [pscustomobject]@{ Name = $s.Name; IP = $s.IP; Role = $s.Role } }
$report | Format-Table | Export-Csv ./nightly.csv
$checks = $report | ForEach-Object -Parallel { [pscustomobject]@{ Name = $_.Name; Env = $Env } }
$summary = @{ env = $Env; count = $report.Count; servers = $report; checks = $checks }
$summary | ConvertTo-Json | Set-Content ./nightly.json
Write-Host "Done: $summary.count servers"
if ($checks.Env -contains $null) { exit 3 }
Run it like the scheduler (which uses -Command)
pwsh -NoProfile -Command ./nightly-broken.ps1; "exit=$LASTEXITCODE"
Get-Content ./nightly.csv -TotalCount 1
(Get-Content ./nightly.json -Raw | ConvertFrom-Json).count
Done: System.Collections.Hashtable.count servers
exit=1
"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
6
Find the faults (8 or more), then compare:
Answer: the faults and their issue numbers
  1. $_.Monitored is a string → 6 prod servers instead of 4 (#7).
  2. ? alias and untyped, unvalidated $Env parameter (#4; Q16) — $Env also looks like the env: drive to readers.
  3. Relative ../data depends on the caller's location (Hour 1; use $PSScriptRoot).
  4. += in a loop (#20).
  5. Format-Table | Export-Csv → ClassId… CSV (#1).
  6. $Env inside -Parallel without $using: → every check has Env = $null (#30).
  7. @{} unordered and ConvertTo-Json default depth 2 for nested servers and checks (#19, #10).
  8. "$summary.count" prints System.Collections.Hashtable.count (#3); Write-Host for a status line (Q6).
  9. The job meant to exit 3, but the scheduler's -Command turned it into 1 (#5); no $ErrorActionPreference, no StrictMode (#26, #11).
The fixed job — save as ~/pslab/lab9/nightly.ps1:
[CmdletBinding()]
param([ValidateSet('dev', 'staging', 'prod')][string]$Environment = 'prod')
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$data = Join-Path $PSScriptRoot '..' 'data' 'servers.csv'
$servers = Import-Csv -LiteralPath $data | Where-Object { $_.Monitored -eq 'true' -and $_.Env -eq $Environment }
$report = foreach ($s in $servers) {
    [pscustomobject]@{ Name = $s.Name; IP = $s.IP; Roles = @($s.Role -split ',') }
}
$report | Select-Object Name, IP, @{ n = 'Roles'; e = { $_.Roles -join ';' } } |
    Export-Csv -LiteralPath (Join-Path $PSScriptRoot 'nightly.csv')
$checks = $report | ForEach-Object -ThrottleLimit 8 -Parallel {
    [pscustomobject]@{ Name = $_.Name; Env = $using:Environment }
}
$summary = [ordered]@{ env = $Environment; count = @($report).Count; servers = @($report); checks = @($checks) }
ConvertTo-Json -InputObject $summary -Depth 5 | Set-Content -LiteralPath (Join-Path $PSScriptRoot 'nightly.json')
Write-Information "Done: $($summary.count) servers" -InformationAction Continue
if (@($checks).Count -ne $summary.count) { exit 1 }
exit 0
Prove it
pwsh -NoProfile -NonInteractive -File ./nightly.ps1 -Environment prod; "exit=$LASTEXITCODE"
Get-Content ./nightly.csv
$j = Get-Content ./nightly.json -Raw | ConvertFrom-Json
"$($j.env) $($j.count) $($j.servers[0].Roles -join '+') $($j.checks.Env | Sort-Object -Unique)"
Done: 4 servers
exit=0
"Name","IP","Roles"
"web-01","10.30.1.41","web"
"web-02","10.30.1.42","web"
"api-01","10.30.1.43","api"
"edge-01","10.30.2.51","web;api"
prod 4 web prod
Acceptance criteria

II. Full mock interview (10 random questions from 50)

III. Open-ended self-check

1. Explain to a junior engineer why try/catch did not catch a failed Remove-Item, in three sentences.

Cmdlets report most failures as non-terminating errors: they write an error record and continue. catch only receives terminating errors. Add -ErrorAction Stop (or set $ErrorActionPreference = 'Stop') so the failure becomes terminating.

2. Name the three boundaries a value can cross in PowerShell and what each one changes.

Scope/module boundary (variables and preferences visible or not, #27, #50); runspace boundary (no caller variables or functions, $using: shares references, #30–#33); process/machine boundary (serialization to Deserialized objects, authentication, #29, #31).

3. Which five Part A issues would you turn into PSScriptAnalyzer rules or CI checks first, and which can only be caught by tests?

Analyzer/CI: aliases (#4), null comparison (#8), missing $using: (#30), plain-text secrets (#44), BOM (#46); launcher line check (#5, #6). Tests only: CSV booleans (#7), unrolling (#9), races (#33), WhatIf propagation (#50), culture (#22, #24).

4. A teammate wants to “just add -ExecutionPolicy Bypass and TrustedHosts *” to make remoting work. Respond.

Bypass in the process scope is fine for automation — execution policy is not a boundary (#45). TrustedHosts * disables server authentication for NTLM connections to every host (#37); use Kerberos with names, HTTPS or SSH remoting, or a specific host list.

IV. Final quiz (12 questions)

Sources and version notes

Version facts were checked on 2026-11-24 against Microsoft Learn, the PowerShell Gallery and YouTube oEmbed; outputs were produced on PowerShell 7.6.10 (Windows 11, .NET 10.0.15) and Windows PowerShell 5.1.26100
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
ReleasesPowerShell 7.6 is the current LTS (GA 2026-03-18, .NET 10, EOS 2028-11-14); 7.4 and 7.5 reached end of support 2026-11-10; 7.7 preview. Lab machine 7.6.10 / .NET 10.0.15; bundled Microsoft.PowerShell.ThreadJob 2.2.0 and PSResourceGet 1.2.1PowerShell support lifecycle; What's New in PowerShell 7.6; local $PSVersionTable, Get-Module -ListAvailable
PesterIn-box Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules is found by pwsh; Pester 6.2.0 saved from the Gallery provides the Should-* functions (41 listed) and ran the Q33 testsPester installation; Pester on the PowerShell Gallery; runs for #39 and Q33
PSScriptAnalyzerVersion 1.25.0 from the Gallery; rules seen in Q35 output; no rule fired for SupportsShouldProcess without a ShouldProcess call; compatibility rules PSUseCompatibleCommands/Syntax/Types presentPSScriptAnalyzer rules; Q35 run
Errors and native commandsNon-terminating errors are not caught (#26); $PSNativeCommandUseErrorActionPreference throws NativeCommandExitException (#28)about_Preference_Variables; Everything about exceptions
ParallelismDefault ThrottleLimit 5 measured (10 × 1 s ≈ 2.3 s); script-block $using: rejected; race reproduced (1999/2000); Start-Job ≈ 4× slower to start than thread jobs on the lab machineForEach-Object; about_Remote_Variables
Web cmdlets-ConnectionTimeoutSeconds (alias -TimeoutSec) and -OperationTimeoutSeconds default 0 = indefinite; error body in ErrorDetails.Message; built-in retry at a fixed intervalInvoke-RestMethod; local mock API runs
Modules and editionsPSModulePath composition; CompatiblePSEditions checked only for System32 modules (Desktop-only test module imported from another path without error)about_PSModulePath; about_PowerShell_Editions
Encodingpwsh writes UTF-8 without BOM; 5.1 > writes UTF-16 LE with BOM (255 254); with code page 1252 the bytes decode as caféabout_Character_Encoding; #46 runs
Remoting and securitySecond hop options; TrustedHosts behaviour; execution policy is not a security boundaryMaking the second hop; about_Execution_Policies; about_Language_Modes
Azure contextContext autosave and explicit subscription selectionAzure PowerShell context persistence
DatasetAll dataset facts used here (611 lines, 20 × 5xx all on /api/orders, 12 servers, 8 monitored, 2,918,056 bytes) re-checked by the labs in Modules 2, 6 and 8Hour 1 New-LabData.ps1; actual runs

Video verification notes

Only videos whose title and channel were checked with YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24 are listed:

oEmbed verifies titles and channels only; the videos were not reviewed segment by segment and may use older PowerShell or Pester versions — where they differ, this lesson's verified runs are authoritative. No verified video was found for wildcard paths/unrolling/JSON depth, culture-dependent parsing, PSModulePath on CI, 5.1↔7 encodings, -WhatIf across module boundaries or PowerShell code review.

Voice narration notes

The Voice tab uses the browser's Web Speech API (en-US); no network or external scripts. Narration scripts can be reused for TTS or recording.

Known limitations

  • Run environment: Windows 11, pwsh 7.6.10, culture en-US, ANSI code page 65001. Because of the code page, Windows PowerShell 5.1 read the BOM-less UTF-8 file correctly in #46; the mojibake for code page 1252 was produced by decoding the same bytes with code page 1252 in pwsh, not by a 5.1 run on a 1252 machine. Paths were replaced with C:\Users\labadmin\pslab\….
  • Not run (Expected output): #31 double hop (needs a domain), #37 TrustedHosts/WinRM (the lab machine's WinRM was not changed), #43 Azure context (no cloud sign-in), the Linux side of #4 and #47 (no Linux run), the profile-loaded side of #6 (the real user profile was not modified). Interview code that needs remoting, Azure, Key Vault/SecretManagement vaults, scheduled tasks or a private feed (Q39–Q50) was reviewed but not executed, except where an output is shown.
  • Timings (#20, #35, #36) and the race count (#33) vary by machine and run; the ratios and the existence of lost updates are the point.
  • Tool versions: Pester 6.2.0 and PSScriptAnalyzer 1.25.0 were the Gallery versions saved on 2026-11-24 into a lab folder (no install scope touched); later versions may add rules or change output.
  • The animations simplify the engine (no dynamic parameters, simplified binding order and serialization depth rules).