PowerShell Lesson 1: How PowerShell Works — Objects, Commands and the Pipeline
grep, awk and cut. PowerShell keeps the same command-line workflow but passes .NET objects through the pipeline, so most text parsing disappears. This course is a systematic deep dive into PowerShell 7 itself: the engine and pipeline, the language, advanced functions, modules, error handling, remoting, cloud automation and testing, applied to a module that grows through the course: OpsKit (created in Lesson 3, released as v1.0 in Lesson 8).- Explain the difference between PowerShell 7 (
pwsh) and Windows PowerShell 5.1 (powershell.exe), what a host is, and which profile files load at startup — including the fact thatpwsh -Filestill loads profiles unless you pass-NoProfile. - Use
Get-Command -Allto see whether a name is an alias, function, cmdlet, script or native program, and apply the command precedence rules (alias → function → cmdlet → external). - Read a syntax diagram — parameter sets, positional and mandatory parameters,
[<CommonParameters>]— and find examples withGet-Help -Examples. - Treat command output as objects: inspect them with
Get-Member, and know why Format-* must come last in a pipeline. - Predict pipeline parameter binding:
ByValuefirst, thenByPropertyName— this lesson's core animation — and confirm it withTrace-Command. - Filter and shape data with
Where-Object,Select-Object(calculated properties),Sort-Object,Group-ObjectandMeasure-Object, and know when to filter left. - Predict how a line is parsed in expression mode vs argument mode; choose single quotes, double quotes,
$( ), here-strings and the backtick correctly; and use-LiteralPathfor names like[draft] notes.md. - Write a first .ps1 script with
param(),$PSScriptRootand explicitexitcodes, run it with&, dot-sourcing andpwsh -File, and know whypwsh -Commandcan turn exit code 3 into 1.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interactive | Lab (~/pslab) |
|---|---|---|---|---|---|
| 0 | Before Class | Environment setup | PowerShell 7.6 on Windows / macOS / Linux / container, VS Code + PowerShell extension, ~/pslab, New-LabData.ps1 to generate the sample dataset | Environment self-check checklist | Generate ~/pslab/data/ and verify SHA-256 hashes |
| 1 | 00–06 | What PowerShell is | Engine, host, runspace; pwsh vs powershell.exe; .NET 10; LTS lifecycle; profiles; -NoProfile, -File, -Command | Startup simulator: which profiles and settings load | Identify edition, host and profile paths |
| 2 | 06–13 | Commands | Cmdlet, function, alias, filter, ExternalScript, Application; Verb-Noun; precedence; module-qualified names | Command resolver | Make one name an alias, a function and a cmdlet at once |
| 3 | 13–21 | Discovery | Get-Command, Get-Help, -Examples, about_* topics, syntax diagrams, parameter sets, Get-Verb | Syntax diagram decoder | Answer questions about a cmdlet using only help |
| 4 | 21–28 | Objects and formatting | .NET types, properties, methods, Get-Member, PSCustomObject, default views, Format-Table / Format-List, “format right” | Object vs text: what travels down the pipe | Inspect Import-Csv and Get-Item objects |
| 5 | 28–35 | Pipeline and binding | Streaming one object at a time; begin / process / end; ByValue, ByPropertyName, aliases such as PSPath; Trace-Command | core animation: pipeline parameter binding | Prove which parameter receives a FileInfo object |
| 6 | 35–42 | Filtering and shaping | Where-Object, Select-Object, calculated properties, Sort-Object, Group-Object, Measure-Object, .Where(), filter left | Pipeline stage-by-stage data view | Server inventory report from servers.csv |
| 7 | 42–50 | Parsing and quoting | Expression vs argument mode; quotes; $( ); here-strings; backtick; --; --%; native arguments; wildcards and -LiteralPath | Interactive parser: how is this line read? | Handle the odd file names in files/ |
| 8 | 50–60 | First script | .ps1, param(), #Requires, execution policy, & vs ., $PSScriptRoot, exit, $LASTEXITCODE, -File vs -Command | Script run path animation + troubleshooting tree | Write ~/pslab/scripts/Get-DataInfo.ps1 |
| — | After Class | Cheat sheet · Integrated lab | Write Test-LabData.ps1: validate the dataset with objects, handle odd names safely and return meaningful exit codes | Final quiz (12 questions) | The script passes every check on ~/pslab/data |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Identify edition, host and startup behavior | ✓ | · | · | · | · | · | · | ✓ | $PSVersionTable, $Host.Name, $PROFILE, pwsh -NoProfile | M1 |
| Distinguish command types and precedence | · | ✓ | ✓ | · | · | · | ✓ | ✓ | Get-Command -All, Get-Alias, Module\Cmdlet | M2 |
| Discover commands and read help | · | ✓ | ✓ | ✓ | ✓ | · | · | · | Get-Help -Examples, Get-Command -Syntax, Get-Verb | M3 |
| Work with objects and formatting | · | · | · | ✓ | ✓ | ✓ | · | ✓ | Get-Member, Format-Table, [pscustomobject] | M4, integrated lab |
| Predict pipeline parameter binding | · | · | ✓ | ✓ | ✓ | ✓ | · | · | Trace-Command ParameterBinding, -PipelineVariable | M5 |
| Filter, sort, group and measure | · | · | · | ✓ | ✓ | ✓ | · | ✓ | Where-Object, Select-Object, Group-Object, Measure-Object | M6, integrated lab |
| Quote and escape correctly | · | · | · | · | · | ✓ | ✓ | ✓ | '…', "…$( )…", @' '@, `, -LiteralPath | M7, integrated lab |
| Write and run scripts with exit codes | ✓ | ✓ | · | · | · | · | ✓ | ✓ | param(), exit, $LASTEXITCODE, pwsh -File | M8, integrated lab |
Excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
Type system details, operators (-eq on arrays, -match, -replace), arrays, hashtables, switch, loops, regex, JSON / CSV conversion | Needs the object and parsing model from this lesson first | Lesson 2: Language Essentials |
Functions, scope, [CmdletBinding()], parameter validation, writing pipeline-aware functions | Belongs to tool-making | Lesson 3 |
| Modules, PSResourceGet, providers in depth, cross-platform paths and encodings | Packaging and environment | Lesson 4 |
Terminating vs non-terminating errors, try/catch, streams, -WhatIf | This lesson only previews exit codes | Lesson 5 |
Remoting, jobs, ForEach-Object -Parallel, scheduling | Multi-machine administration | Lesson 6 |
| REST APIs, Az and AWS.Tools modules, secrets | Cloud automation | Lesson 7 (also Azure and AWS courses) |
| Pester, PSScriptAnalyzer, debugging, signing, CI | Quality and release | Lesson 8 |
How to use these materials
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Read “Principles” and “Animation” first, then do the “Lab” in
~/pslab. The pipeline binding animation in Module 5 is the main thread of the whole course.A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
$PSVersionTable as the reference. PowerShell 7.4 LTS and 7.5 both reached end of support on 2026-11-10; 7.7 is in preview. Windows PowerShell 5.1 still ships with Windows and is maintained, but gets no new features; differences that matter are called out in each module. All lab steps work on Windows, macOS and Linux unless a step is marked “Windows only”.Module 0 · Environment setup: PowerShell 7.6, VS Code and ~/pslab
~/pslab, and use New-LabData.ps1 to generate the sample dataset ~/pslab/data/ that Lessons 2–9 use directly- Comfortable with a terminal (any shell). The Bash course is helpful for comparison but not required.
- One of the environments in the table below. Not required: a cloud account (only Lesson 7 uses one, and it is optional), administrator rights after installation.
- An editor: VS Code with the PowerShell extension (recommended; it gives IntelliSense, PSScriptAnalyzer warnings and a debugger). The old Windows PowerShell ISE only supports 5.1 and is not used in this course.
Choose an environment
| Option | How to install | Notes |
|---|---|---|
| A. Windows 11 / Windows Server (recommended for Lessons 6 and 8) | winget install --id Microsoft.PowerShell --source winget | Installs to C:\Program Files\PowerShell\7 side by side with Windows PowerShell 5.1. Start it as pwsh. Windows Terminal picks it up automatically. |
| B. macOS | brew install --cask powershell | The official PKG from GitHub releases also works and is signed and notarized by Microsoft from 7.6. |
| C. Linux (Ubuntu, Debian, RHEL) | Register the Microsoft package repository for your distribution, then sudo apt-get install powershell or sudo dnf install powershell | Follow “Installing PowerShell on Linux” on Microsoft Learn for the exact repository package of your release. The Linux course VM linuxlab works well. |
| D. Container | docker run --rm -it -v "$HOME/pslab:/root/pslab" -w /root/pslab mcr.microsoft.com/powershell:lts | Linux-based image; good for testing cross-platform behavior. Use the -v mount so the data stays on the host. Check available tags in the Microsoft Artifact Registry before pinning one. |
You can do most of Lesson 1 in Windows PowerShell 5.1, but outputs and some behavior differ (for example, native argument passing and the default file encoding). Wherever this course says pwsh, use PowerShell 7.
Confirm the version
$PSVersionTable.PSVersion.ToString() $PSVersionTable.PSEdition [System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription $Host.Name
7.6.10 Core .NET 10.0.15 ConsoleHost
Core means PowerShell 6 or later; Windows PowerShell 5.1 reports Desktop. The patch number depends on when you installed it. In the VS Code PowerShell extension terminal, $Host.Name is Visual Studio Code Host — the host matters for profiles (Module 1).
Create the working folder
$lab = Join-Path $HOME 'pslab'
'data', 'scripts', 'tmp' | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path $lab $_) -Force } | Out-Null
Set-Location $lab
Get-ChildItem -Name
data scripts tmp
| Folder | Purpose | Which lessons use it |
|---|---|---|
~/pslab/data/ | Sample dataset (generated by New-LabData.ps1; can be rebuilt at any time) | All lessons |
~/pslab/scripts/ | Practice scripts | All lessons |
~/pslab/tmp/ | Temporary output from labs; safe to delete | All lessons |
~/pslab/OpsKit/ | Running project: the OpsKit module (Public/, Private/, OpsKit.psd1, tests/) | Created in Lesson 3, packaged in Lesson 4, evolved in Lessons 5–7, released as v1.0 in Lesson 8 |
~ works in PowerShell paths on every platform: it resolves to $HOME (C:\Users\<you> on Windows, /home/<you> on Linux). Join-Path picks the right separator; with PowerShell 7 it also accepts several child paths at once.
New-LabData.ps1: generate the course's sample dataset
Save the script below as ~/pslab/New-LabData.ps1 (in VS Code: File → New File, paste, save with the .ps1 extension). It is deterministic: it does not use Get-Random or the current time, but a fixed-seed linear congruential generator, so every machine produces byte-identical files and later lessons can refer to facts such as “line 307” or “20 lines with a 5xx status”. It writes UTF-8 without a BOM and LF line endings on every platform.
<#
.SYNOPSIS
Generates the sample dataset for the PowerShell 8 + 1 hour course.
.DESCRIPTION
Deterministic: no Get-Random and no current time, so every machine produces
byte-identical files. Run it again at any time to rebuild the data folder.
.EXAMPLE
./New-LabData.ps1
./New-LabData.ps1 -Path ~/pslab/data
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
[string]$Path = (Join-Path $HOME 'pslab' 'data')
)
$ErrorActionPreference = 'Stop'
# Safety guard: only delete and recreate a folder whose name is exactly "data".
if ((Split-Path $Path -Leaf) -ne 'data') {
throw "New-LabData: the target folder must be named 'data': $Path"
}
if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Recurse -Force }
$null = New-Item -ItemType Directory -Path (Join-Path $Path 'files' 'sub dir')
# ---------- deterministic pseudo-random numbers (linear congruential generator) ----------
$script:seed = [long]20261125
function Get-Next([int]$Max) {
$script:seed = ($script:seed * 1103515245 + 12345) % 2147483648
[int](($script:seed -shr 16) % $Max)
}
$utf8 = [System.Text.UTF8Encoding]::new($false) # UTF-8 without BOM, LF line endings
function Write-LabFile([string]$File, [string[]]$Lines) {
[System.IO.File]::WriteAllText($File, (($Lines -join "`n") + "`n"), $utf8)
}
# ---------- 1) access.log: nginx combined format ----------
$ips = '203.0.113.7','198.51.100.23','192.0.2.10','192.0.2.11','192.0.2.12',
'10.10.1.21','10.10.1.22','10.20.1.31','172.16.5.4','203.0.113.99'
$paths = '/','/healthz','/healthz','/api/orders','/api/orders','/api/orders',
'/api/orders/1042','/login','/static/app.js'
$uas = 'curl/8.12.1',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15',
'kube-probe/1.37',
'PowerShell/7.6 (Windows NT 10.0)'
$log = [System.Collections.Generic.List[string]]::new()
$t = 10 * 3600
function Add-Line($Ip, $Method, $Url, $Status, $Bytes, $Ua) {
$ts = '24/Nov/2026:{0:00}:{1:00}:{2:00} +0000' -f [int][math]::Floor($t / 3600), [int][math]::Floor(($t % 3600) / 60), ($t % 60)
$log.Add(('{0} - - [{1}] "{2} {3} HTTP/1.1" {4} {5} "-" "{6}"' -f $Ip, $ts, $Method, $Url, $Status, $Bytes, $Ua))
}
$t++
Add-Line '203.0.113.7' 'GET' '/healthz' 200 2 'curl/8.12.1'
for ($i = 2; $i -le 600; $i++) {
$t += Get-Next 7
$ip = $ips[(Get-Next $ips.Count)]
$p = $paths[(Get-Next $paths.Count)]
$ua = $uas[(Get-Next $uas.Count)]
$m = 'GET'
switch ($p) {
'/healthz' { $st = 200; $bytes = 2; $ua = 'kube-probe/1.37' }
'/login' { if ((Get-Next 4) -eq 0) { $m = 'POST'; $st = 302; $bytes = 0 } else { $st = 200; $bytes = 1532 } }
'/api/orders' {
if ((Get-Next 3) -eq 0) { $m = 'POST' }
$r = Get-Next 20
if ($r -eq 0) { $st = 500; $bytes = 0 }
elseif ($r -eq 1) { $st = 503; $bytes = 0 }
elseif ($r -eq 2) { $st = 400; $bytes = 48 }
elseif ($m -eq 'POST'){ $st = 201; $bytes = 180 + (Get-Next 400) }
else { $st = 200; $bytes = 900 + (Get-Next 4000) }
}
'/api/orders/1042' { if ((Get-Next 5) -eq 0) { $st = 404; $bytes = 21 } else { $st = 200; $bytes = 300 + (Get-Next 5) } }
'/static/app.js' { if ((Get-Next 3) -eq 0) { $st = 304; $bytes = 0 } else { $st = 200; $bytes = 48213 } }
'/' { if ((Get-Next 6) -eq 0) { $st = 301; $bytes = 169 } else { $st = 200; $bytes = 4120 } }
}
Add-Line $ip $m $p $st $bytes $ua
if ($i -eq 150) { 1..6 | ForEach-Object { $t++; Add-Line '198.51.100.23' 'POST' '/login' 401 64 'python-requests/2.32.5' } }
if ($i -eq 300) { $t += 2; Add-Line '192.0.2.66' 'GET' '/' 200 4120 "O'Reilly-Bot/2.0 (it's \x22quoted\x22; +https://example.com/bot)" }
if ($i -eq 450) { 1..4 | ForEach-Object { $t++; Add-Line '10.20.1.31' 'GET' '/api/orders' 502 157 'curl/8.12.1' } }
}
Write-LabFile (Join-Path $Path 'access.log') $log
# ---------- 2) servers.csv and 3) inventory.json: the same 12 servers ----------
$servers = @(
'web-01|dev|canadacentral|10.10.1.21|web|true'
'api-01|dev|canadacentral|10.10.1.22|api|true'
'db-01|dev|canadacentral|10.10.1.23|db|false'
'web-01|staging|ca-central-1|10.20.1.31|web|true'
'api-01|staging|ca-central-1|10.20.1.32|api|true'
'db-01|staging|ca-central-1|10.20.1.33|db|false'
'web-01|prod|canadacentral|10.30.1.41|web|true'
'web-02|prod|canadacentral|10.30.1.42|web|true'
'api-01|prod|canadacentral|10.30.1.43|api|true'
'edge-01|prod|ca-central-1|10.30.2.51|web,api|true'
'db-01|prod|canadacentral|10.30.1.44|db|false'
'bastion-01|prod|ca-central-1|10.30.2.10|bastion|false'
)
$csv = [System.Collections.Generic.List[string]]::new()
$json = [System.Collections.Generic.List[string]]::new()
$csv.Add('Name,Env,Region,IP,Role,Monitored')
$json.Add('[')
for ($k = 0; $k -lt $servers.Count; $k++) {
$f = $servers[$k] -split '\|'
$role = if ($f[4] -like '*,*') { '"{0}"' -f $f[4] } else { $f[4] }
$csv.Add(('{0},{1},{2},{3},{4},{5}' -f $f[0], $f[1], $f[2], $f[3], $role, $f[5]))
$sep = if ($k -lt $servers.Count - 1) { ',' } else { '' }
$json.Add((' {{"Name": "{0}", "Env": "{1}", "Region": "{2}", "IP": "{3}", "Role": "{4}", "Monitored": {5}, "Port": 8080}}{6}' -f $f[0], $f[1], $f[2], $f[3], $f[4], $f[5], $sep))
}
$json.Add(']')
Write-LabFile (Join-Path $Path 'servers.csv') $csv
Write-LabFile (Join-Path $Path 'inventory.json') $json
# ---------- 4) opskit.config.psd1: configuration for the OpsKit module (Hour 3 onward) ----------
$config = @'
# OpsKit sample configuration (PowerShell course). Read with Import-PowerShellDataFile.
@{
Version = '0.1'
LogLevel = 'Information' # Verbose | Information | Warning | Error
DefaultEnv = 'dev'
Inventory = '~/pslab/data/servers.csv'
Environments = @{
dev = @{ Region = 'canadacentral'; HealthUrl = 'http://10.10.1.21:8080/healthz' }
staging = @{ Region = 'ca-central-1'; HealthUrl = 'http://10.20.1.31:8080/healthz' }
prod = @{ Region = 'canadacentral'; HealthUrl = 'https://shop.example.com/healthz'; RequireConfirm = $true }
}
Health = @{ TimeoutSec = 5; Retries = 3; BackoffSec = @(1, 2, 4) }
Backup = @{ Destination = '~/pslab/backups'; Keep = 7; Exclude = @('*.tmp', '.cache') }
}
'@
Write-LabFile (Join-Path $Path 'opskit.config.psd1') ($config -split "`r?`n")
# ---------- 5) files/: names that break naive scripts (all legal on Windows, macOS and Linux) ----------
$names = @(
'report 2026.txt' # space
'two spaces.txt' # two spaces
'[draft] notes.md' # square brackets: wildcard characters in -Path
'price $5.txt' # dollar sign: expands inside double quotes
"it's.txt" # single quote
'tick`mark.txt' # backtick: the PowerShell escape character
'-WhatIf.txt' # looks like a parameter
'#hash.txt' # starts with a comment character
'a&b;c.txt' # & and ; are operators in argument mode
'café-ünïcode.txt' # non-ASCII
'.hidden.txt' # hidden on Linux/macOS, not on Windows
'sub dir/nested file.log' # folder with a space
)
$fileDir = Join-Path $Path 'files'
$n = 0
foreach ($name in $names) {
$n++
$full = Join-Path $fileDir $name
[System.IO.File]::WriteAllText($full, "file #$n`n", $utf8)
(Get-Item -LiteralPath $full -Force).LastWriteTimeUtc = [datetime]::new(2026, 11, 24, 9, $n, 0, [DateTimeKind]::Utc)
}
(Get-Item -LiteralPath (Join-Path $fileDir 'sub dir')).LastWriteTimeUtc = [datetime]::new(2026, 11, 24, 9, 0, 0, [DateTimeKind]::Utc)
[pscustomobject]@{
Path = (Resolve-Path -LiteralPath $Path).Path
AccessLog = $log.Count
Servers = $servers.Count
Files = $names.Count
}
Set-Location ~/pslab
./New-LabData.ps1
Get-ChildItem ./data -File | Get-FileHash |
ForEach-Object { '{0} {1}' -f $_.Hash.Substring(0, 16), (Split-Path $_.Path -Leaf) }
Path AccessLog Servers Files ---- --------- ------- ----- C:\Users\labadmin\pslab\data 611 12 12 A0A0D5B9D3B4C974 access.log 6E3808C1DB0D3276 inventory.json 381E684642929B30 opskit.config.psd1 6323C180C2EFF12E servers.csv
The SHA-256 prefixes are identical on Windows, macOS and Linux. If they differ, the usual causes are a damaged paste (an editor replaced straight quotes with curly quotes) or running it in Windows PowerShell 5.1 (the script needs 7.4+ because of #Requires -Version 7.4). If you see “running scripts is disabled on this system”, jump to Module 8's execution policy section, then come back. The script can be run repeatedly; each run deletes and recreates data/.
Dataset overview (conventions used throughout the course)
| File | Contents | Facts worth remembering (used in later lessons) |
|---|---|---|
access.log | 611 lines of nginx combined access log, 2026-11-24 10:00:01–10:29:50 (UTC); methods GET 526 / POST 85 | Line 1 is 203.0.113.7 … "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"; status codes 200×463, 201×54, 301×12, 302×17, 304×18, 400×3, 401×6, 404×18, 500×8, 502×4, 503×8 (5xx total 20); paths /api/orders 216, /healthz 124, / 75, /login 69, /api/orders/1042 64, /static/app.js 63; busiest client 198.51.100.23 (72 requests); lines 151–156: 6 consecutive POST /login 401s from 198.51.100.23; line 307: a User-Agent containing an apostrophe and nginx-escaped quotes \x22; lines 458–461: four 502s from 10.20.1.31; total bytes 2,918,056 |
servers.csv | Header Name,Env,Region,IP,Role,Monitored + 12 rows; dev 3 / staging 3 / prod 6 | Row edge-01,prod,ca-central-1,10.30.2.51,"web,api",true has a quoted comma: Import-Csv handles it correctly, naive -split ',' does not; Name is not unique (every environment has web-01); Monitored is the string "true"/"false" after Import-Csv — and [bool]'false' is $true (Module 6) |
inventory.json | The same 12 servers as JSON, plus "Port": 8080; here Monitored is a real boolean | Compared with the CSV in Lesson 2 (ConvertFrom-Json keeps types; CSV makes everything a string) |
opskit.config.psd1 | A PowerShell data file: the OpsKit configuration (environments, health check, backup) | Read safely with Import-PowerShellDataFile (no code execution) from Lesson 3 onward |
files/ | 12 “odd names”, all legal on Windows, macOS and Linux: spaces, two spaces, [draft] notes.md, price $5.txt, it's.txt, tick`mark.txt, -WhatIf.txt, #hash.txt, a&b;c.txt, café-ünïcode.txt, .hidden.txt, sub dir/nested file.log | Contents file #1 … file #12; modification times 09:01 … 09:12 UTC (sub dir 09:00). Get-ChildItem files -File returns 11 on Windows but 10 on Linux/macOS, because .hidden.txt is hidden only on Unix-like systems — add -Force to see it everywhere |
Environment self-check checklist
Remove-Item, overwriting with Set-Content or >) is limited to ~/pslab. Never copy a Remove-Item -Recurse -Force line into another folder without reading it first. You can always rebuild the dataset with ~/pslab/New-LabData.ps1; full cleanup is Remove-Item -LiteralPath ~/pslab -Recurse -Force (Lessons 2–9 still use it, so keep it).Module 1 · What PowerShell Is: engine, hosts, editions and startup
- Distinguish the terminal, the host and the engine, and know that
pwshandpowershell.exeare different products that install side by side. - Read
$PSVersionTable,$Host.Nameand$PSEdition, and know whatCorevsDesktopmeans. - Name the four profile paths in
$PROFILEand say which ones load for a given host. - Explain
-NoProfile,-NonInteractive,-Fileand-Command, and know that profiles load for scripts too unless you pass-NoProfile— the opposite of Bash, where scripts read no rc files.
What: terminal, host and engine
| Layer | What it is | Examples |
|---|---|---|
| Terminal | Draws characters and sends keystrokes (ConPTY on Windows, a pty on Unix) | Windows Terminal, iTerm2, GNOME Terminal, the VS Code terminal panel |
| Host | A program that embeds the PowerShell engine and provides the UI: prompt, line editing (PSReadLine), how output and prompts are shown. $Host.Name identifies it. | ConsoleHost (pwsh), Visual Studio Code Host, a custom C# app, Azure Functions, the ServerRemoteHost on the remote side of a session |
| Engine + runspace | System.Management.Automation.dll: parser, command discovery, parameter binder, pipeline processor, formatting. A runspace holds the session state: variables, functions, drives, modules, current location. | Same engine in every host; one host can open several runspaces (jobs, -Parallel, remoting) |
| .NET runtime | Everything PowerShell returns is a .NET object; cmdlets are .NET classes | PowerShell 7.6 → .NET 10; Windows PowerShell 5.1 → .NET Framework 4.x |
Why: two editions, one name
| PowerShell 7.x (“Core”) | Windows PowerShell 5.1 (“Desktop”) | |
|---|---|---|
| Executable | pwsh / pwsh.exe | powershell.exe |
| Platforms | Windows, macOS, Linux | Windows only |
| Runtime | .NET (7.6: .NET 10) | .NET Framework 4.x |
| Status | Active development; LTS releases follow .NET LTS | Ships in Windows, security fixes only, no new features |
| Profile folder (Windows) | Documents\PowerShell | Documents\WindowsPowerShell |
| Module folder (Windows) | Documents\PowerShell\Modules + $PSHOME\Modules | Documents\WindowsPowerShell\Modules |
| Default file encoding | UTF-8 without BOM | Varies by cmdlet (UTF-16 LE for >, ANSI for Set-Content) |
Because they install side by side and keep separate profiles and module folders, “I installed the module but the command is not found” often means it was installed for the other edition. Always check $PSVersionTable.PSEdition first.
How: the four profiles
$PROFILE property | Windows path (pwsh 7) | Loaded by |
|---|---|---|
AllUsersAllHosts | $PSHOME\profile.ps1 | Every host, every user |
AllUsersCurrentHost | $PSHOME\Microsoft.PowerShell_profile.ps1 | Every user, this host only |
CurrentUserAllHosts | ~\Documents\PowerShell\profile.ps1 | You, every host |
CurrentUserCurrentHost (the value of $PROFILE itself) | ~\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 | You, this host only. VS Code uses Microsoft.VSCode_profile.ps1 instead |
On Linux and macOS the current-user profiles live in ~/.config/powershell/. They load in the order shown (all users before current user, all hosts before current host). If Documents is redirected (OneDrive, a network share), so is your profile — the lab machine's outputs in this lesson show a redirected path for that reason.
When: startup switches that change behavior
| Invocation | Profiles? | Interactive prompts? | Exit code |
|---|---|---|---|
pwsh (in a terminal) | Yes | Yes | — |
pwsh -File ./x.ps1 -Arg 1 | Yes | Yes, unless -NonInteractive | The script's exit N; 1 if it throws |
pwsh -Command "./x.ps1" | Yes | Yes, unless -NonInteractive | 0 or 1, from $? of the last command (Module 8) |
pwsh -NoProfile -NonInteractive -File ./x.ps1 | No | No — a missing mandatory parameter becomes an error | The script's exit N |
powershell and pwsh are the same thing” — different runtime, profiles and module folders. ② “Scripts don't read my profile” — pwsh -File does load profiles; automation should always pass -NoProfile. ③ “Execution policy is a security boundary” — it stops accidental script runs only (Module 8). ④ “$PROFILE is the only profile” — it is one of four. ⑤ “On Linux, ls in PowerShell is Get-ChildItem” — not there; see Module 2.Architecture diagram: from keystroke to formatted output
Flowchart: what loads when pwsh starts
Startup simulator: what is in effect for this invocation?
Choose how PowerShell is started, then step through which profiles load, whether prompts are allowed, and whether the helper function Show-Greeting defined in your profile and the module path you added there are available.
pwsh) parses its command-line switches, reads powershell.config.json, creates the initial runspace, and — unless -NoProfile is present — dot-sources the profile scripts that exist for the current host, in the documented order. Each host has its own host-specific profile file name (Microsoft.PowerShell_profile.ps1, Microsoft.VSCode_profile.ps1). The “all hosts” profiles (profile.ps1) are shared by every host.Command table
| Command | Purpose | Notes |
|---|---|---|
$PSVersionTable | Version, edition, OS, platform | .PSVersion is a [semver]-like object; compare with -ge [version]'7.4' |
$Host.Name | Which host you are in | Decides the host-specific profile |
$PROFILE | Select-Object * | All four profile paths | The paths are NoteProperties on a string |
Test-Path $PROFILE | Does your profile exist? | It is not created automatically |
$PSHOME | Install folder of this edition | C:\Program Files\PowerShell\7 |
pwsh -NoProfile | Start without profiles | Use for all automation and for reproducing bugs |
pwsh -NonInteractive | Never prompt | Prompts (Read-Host, mandatory parameters, -Confirm) become errors |
pwsh -File / -Command | Run a script file / a command string | Exit-code semantics differ (Module 8) |
$IsWindows, $IsLinux, $IsMacOS | Platform checks | Not defined in 5.1 (treat a missing variable as Windows) |
$PSVersionTable.PSVersion.ToString(); $PSVersionTable.PSEdition [System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription $Host.Name $PROFILE | Select-Object * | Format-List
7.6.10 Core .NET 10.0.15 ConsoleHost AllUsersAllHosts : C:\Program Files\PowerShell\7\profile.ps1 AllUsersCurrentHost : C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1 CurrentUserAllHosts : C:\Users\labadmin\Documents\PowerShell\profile.ps1 CurrentUserCurrentHost : C:\Users\labadmin\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 Length : 94
How to verify: Length : 94 gives it away — $PROFILE is a string (the CurrentUserCurrentHost path, 94 characters long) with four extra NoteProperties attached. Common mistake: editing Documents\WindowsPowerShell\… and wondering why pwsh ignores it. Production use: keep profiles short (prompt, PSReadLine options, a few aliases); every new shell pays their cost, and nothing a script needs should live there.
# Compare the two editions on Windows powershell.exe -NoProfile -Command '$PSVersionTable.PSEdition; $PSVersionTable.PSVersion.ToString()' pwsh -NoProfile -Command '$PSVersionTable.PSEdition; $PSVersionTable.PSVersion.ToString()'
Desktop 5.1.26100.1 Core 7.6.10
Goal: Prove by experiment which invocations load your profile. Environment: any PowerShell 7.6. Safety: we never edit your real profile; we create a throw-away profile file under ~/pslab/tmp and dot-source it the same way the host would. Cost: none.
$PROFILE | Select-Object * | Format-List Test-Path $PROFILE.CurrentUserCurrentHost, $PROFILE.CurrentUserAllHosts
…four paths… False False
pwsh -Command '(Get-ChildItem Function:).Count' pwsh -NoProfile -Command '(Get-ChildItem Function:).Count'
If you have no profile at all, both numbers are equal — that is a valid result too. The next step creates a throw-away profile so you can see the difference.
-NoProfile session, exactly like the host does at startup.
$fake = Join-Path ~/pslab/tmp 'fake_profile.ps1'
Set-Content -LiteralPath $fake -Value @'
function Show-Greeting { "Hello from the profile, PowerShell $($PSVersionTable.PSVersion)" }
$env:PSLAB_FROM_PROFILE = '1'
'@
pwsh -NoProfile -Command ". '$fake'; Show-Greeting; `$env:PSLAB_FROM_PROFILE"
pwsh -NoProfile -Command 'Show-Greeting' 2>&1 | Select-Object -First 1
Hello from the profile, PowerShell 7.6.10 1 Show-Greeting: The term 'Show-Greeting' is not recognized as a name of a cmdlet, function, script file, or executable program.
The backtick before $env stops the outer shell from expanding it inside the double-quoted string (Module 7). Dot-sourcing is what makes profile functions visible afterwards (Module 8).
pwsh -NoProfile -NonInteractive -Command 'Read-Host "Name"' 2>&1 | Select-Object -First 1; "exit=$LASTEXITCODE"
Read-Host: PowerShell is in NonInteractive mode. Read and Prompt functionality is not available. exit=1
Remove-Item -LiteralPath (Join-Path ~/pslab/tmp 'fake_profile.ps1')Case 1: a nightly job hangs forever in Task Scheduler
Problem: A scheduled task runs pwsh -File C:\jobs\export.ps1 as a service account. It worked when tested by hand; at night it shows “Running” until someone kills it. Root cause: a mandatory parameter was missing, and without -NonInteractive pwsh waited for keyboard input that never comes. Fix: always run automation with pwsh -NoProfile -NonInteractive -File …, give every mandatory parameter explicitly, and set a task time limit. Caveat: the same happens with -Confirm prompts from cmdlets whose ConfirmImpact is High (Lesson 5).
Case 2: a slow profile makes CI take minutes longer
Problem: On self-hosted build agents, each PowerShell step took 8–15 seconds before doing anything. Root cause: an admin had put Import-Module Az and a Update-Help call in AllUsersAllHosts; CI steps run pwsh without -NoProfile, so every step paid for it. Fix: remove heavy work from profiles, keep machine profiles empty on build agents, and use -NoProfile in your own wrapper commands. GitHub Actions' built-in shell: pwsh runs your step with pwsh -command ". '{0}'", so self-hosted runner profiles do apply there.
Case 3: “the module is installed but the command is not found”
Problem: An engineer installed a module from an elevated powershell.exe, then could not use it in pwsh. Root cause: the module went to Documents\WindowsPowerShell\Modules (5.1's path). Fix: install from the edition you run, and confirm with Get-Module -ListAvailable Name and $env:PSModulePath -split [IO.Path]::PathSeparator (Lesson 4).
Common errors and fixes
pwsh: The term 'pwsh' is not recognized … / command not found: pwsh
Cause: PowerShell 7 is not installed, or the terminal was opened before installation and has an old PATH.
Get-Command pwsh -ErrorAction Ignore $env:PATH -split [IO.Path]::PathSeparator | Select-String PowerShell
Fix: install it (Module 0), then open a new terminal.
My profile changes don't apply in VS Code
Cause: the VS Code host uses its own host-specific profile, Microsoft.VSCode_profile.ps1.
$Host.Name; $PROFILE
Fix: put shared settings in $PROFILE.CurrentUserAllHosts (profile.ps1), which every host loads.
File …profile.ps1 cannot be loaded because running scripts is disabled on this system
Cause: execution policy Restricted (the Windows client default for Windows PowerShell; pwsh on Windows defaults to RemoteSigned).
Get-ExecutionPolicy -List
Fix: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, unless a Group Policy (MachinePolicy / UserPolicy) sets it — then talk to your administrator (Module 8).
Script works interactively, fails or hangs when scheduled
Cause: it relied on something from your profile, on a drive mapping, or on a prompt.
pwsh -NoProfile -NonInteractive -File ./report.ps1
Fix: reproduce exactly like that; make the script self-contained (import its modules, take parameters, never prompt).
1. Write one line that prints the edition, the version and the host name, separated by “ / ”.
"$($PSVersionTable.PSEdition) / $($PSVersionTable.PSVersion) / $($Host.Name)"
Run it in Windows Terminal and in the VS Code extension terminal and compare.
2. Start a clean pwsh that loads no profile and cannot prompt, and print whether your profile file exists.
pwsh -NoProfile -NonInteractive -Command 'Test-Path $PROFILE'
Single quotes keep $PROFILE from being expanded by the current shell, so the child evaluates it (Module 7).
A colleague says: “I set $env:AZURE_SUBSCRIPTION_ID in my profile, and the deployment script works from my terminal, but in the Jenkins agent it deploys to the default subscription.” Analyze and propose a fix.
The Jenkins agent runs under a different account and probably with -NoProfile (or another host), so the variable is not set and the Az module silently uses the default context — a silent failure that is more dangerous than an error. Fix: ① take the subscription as a mandatory script parameter and validate it; ② set it in the pipeline's environment, not in a profile; ③ call Set-AzContext -Subscription $SubscriptionId explicitly and stop if it fails. Principle: a script's runtime environment must be self-contained and must not depend on profiles.
Verified teaching videos
Official documentation
- What is PowerShell? · Differences from Windows PowerShell 5.1 · Support lifecycle
- about_Profiles · about_Pwsh
Video storyboard (about 90 seconds)
These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.
Visual: keyboard → terminal → a “Host” box → an “Engine” box → .NET objects.
Narration: the terminal draws, the host gives you a prompt, the engine runs your pipeline, and everything is a .NET object.
Visual: two icons side by side, pwsh (blue, three OS logos) and powershell.exe (Windows only), each with its own profile and module folder.
Narration: two editions, installed side by side; always check $PSVersionTable first.
Visual: four profile files light up in order; then a “-NoProfile” switch turns them grey.
Narration: four profiles, loaded in order — even for scripts — unless you say -NoProfile.
Visual: a scheduled task spinning forever, then the same task with -NonInteractive failing fast with a clear error.
Narration: automation never prompts. Use -NoProfile and -NonInteractive.
Module 2 · Commands: cmdlets, functions, aliases, scripts and native programs
- Name the command types: Alias, Function, Filter, Cmdlet, ExternalScript, Application (and Configuration), and say where each comes from.
- Apply command precedence: alias → function → cmdlet → external script / application, and bypass it with a module-qualified name or a path.
- Explain the Verb-Noun convention and approved verbs, and why scripts should never use aliases.
- Know that aliases such as
ls,cat,sortandcurldiffer between Windows and Linux/macOS.
What: six kinds of command
| CommandType | What it is | Example | Where it lives |
|---|---|---|---|
| Alias | Another name for a command | gci → Get-ChildItem | Session (Alias: drive), modules |
| Function / Filter | PowerShell code with a name; a filter is a function with only a process block | prompt, mkdir (Windows), your own | Session (Function: drive), script modules |
| Cmdlet | A compiled .NET class deriving from Cmdlet/PSCmdlet | Get-ChildItem | Binary modules (.dll) |
| ExternalScript | A .ps1 file | ./New-LabData.ps1 | Disk; found by path or via PATH |
| Application | Any native executable | git, ping, curl.exe | Disk; found via PATH (+ PATHEXT on Windows) |
Cmdlets and advanced functions follow the Verb-Noun pattern (Get-Process, Stop-Service, New-Item). The verb must come from the approved list (Get-Verb, 100 verbs in 7.6) so that people can guess names: if you know Get-Service, you can guess Start-Service and Stop-Service.
Why: one name, several meanings
Aliases exist for interactive speed and for people coming from cmd.exe or Unix shells. But they are a source of surprises: on Windows ls is an alias for Get-ChildItem; on Linux and macOS PowerShell deliberately does not define ls, cat, sort, cp, mv, rm, ps and similar aliases, so ls runs /bin/ls and returns text. A script that does (ls).Length gets file sizes on Windows and string lengths on Linux.
How: command precedence
- If the name contains a path separator (
./x.ps1,C:\tools\x.exe), run that file. No lookup. - Otherwise: Alias → Function (and filters) → Cmdlet → external (scripts and executables found via
PATH, inPATHorder). - Module auto-loading: if no loaded command matches, PowerShell searches
$env:PSModulePathand imports the module that exports the name. - For security, PowerShell does not run scripts from the current directory by name:
New-LabData.ps1fails;./New-LabData.ps1works.
When: bypassing a layer
| You want | Write |
|---|---|
| The cmdlet even if a function or alias shadows it | Microsoft.PowerShell.Management\Get-ChildItem |
| The native program, not the alias (Windows) | curl.exe, sort.exe, where.exe (add the extension) |
| A specific file | & 'C:\Program Files\Git\bin\git.exe' |
| To see every match in precedence order | Get-Command name -All |
where is the Windows where.exe” — in PowerShell it is the alias for Where-Object; use where.exe or Get-Command. ② “curl is curl” — in Windows PowerShell 5.1 it was an alias for Invoke-WebRequest; PowerShell 7 removed that alias, but scripts written for 5.1 may still rely on it. ③ “Aliases are fine in scripts” — they are not portable and PSScriptAnalyzer flags them (Lesson 8). ④ “A function named like a cmdlet is harmless” — it silently wins.Architecture diagram: where commands come from
Command resolver
Pick a name and a platform, then step through how PowerShell decides what actually runs.
Command reference
| Command | Purpose | Notes |
|---|---|---|
Get-Command name -All | Every command with that name, in precedence order | First row is what runs |
Get-Command -Verb Get -Noun *Item* | Search by verb and noun | Wildcards allowed |
Get-Command -Module Microsoft.PowerShell.Utility | Everything a module exports | Triggers auto-loading |
Get-Alias -Definition Get-ChildItem | Aliases for a command | Get-Alias ls for the reverse |
Module\Command | Run a specific module's command | Bypasses aliases and functions |
(Get-Command x).Source | Module name or file path | For Applications, the full path |
Get-Verb | Approved verbs | Get-Verb -Group Security |
Get-Command ls, dir, cd, curl, where, sort -All |
Format-Table CommandType, Name, Definition -AutoSize
CommandType Name Definition
----------- ---- ----------
Alias ls Get-ChildItem
Application ls.exe C:\Program Files\Git\usr\bin\ls.exe
Alias dir Get-ChildItem
Application dir.exe C:\Program Files\Git\usr\bin\dir.exe
Alias cd Set-Location
Application curl.exe C:\Program Files\Git\mingw64\bin\curl.exe
Application curl.exe C:\Windows\system32\curl.exe
Alias where Where-Object
Application where.exe C:\Windows\system32\where.exe
Alias sort Sort-Object
Application sort.exe C:\Program Files\Git\usr\bin\sort.exe
Application sort.exe C:\Windows\system32\sort.exe
How to verify: the first row for each name wins. curl has no alias in PowerShell 7, so the first curl.exe on PATH runs — here Git's copy, not Windows' own. Common mistake: expecting sort to call sort.exe. Production use: in scripts write full cmdlet names and, for native tools, the explicit .exe on Windows.
Get-Command Get-ChildItem | Format-List Name, CommandType, Source, Version, ImplementingType
Name : Get-ChildItem CommandType : Cmdlet Source : Microsoft.PowerShell.Management Version : 7.0.0.0 ImplementingType : Microsoft.PowerShell.Commands.GetChildItemCommand
ImplementingType is the .NET class behind the cmdlet. The module version of the built-in modules stays at 7.0.0.0 even in PowerShell 7.6.
Goal: Make one name resolve to three different things and learn to bypass each layer. Environment: any pwsh 7.6, inside ~/pslab. Cost: none; all changes vanish when the session closes.
Set-Location ~/pslab
function Get-ChildItem { 'my function wins' }
Get-ChildItem
Microsoft.PowerShell.Management\Get-ChildItem -Name data
my function wins files access.log inventory.json opskit.config.psd1 servers.csv
Set-Alias -Name Get-ChildItem -Value Get-Date # an alias can even use a cmdlet's name Get-Command Get-ChildItem -All | Format-Table CommandType, Name, Definition (Get-ChildItem).GetType().Name
CommandType Name Definition
----------- ---- ----------
Alias Get-ChildItem Get-Date
Function Get-ChildItem 'my function wins'
Cmdlet Get-ChildItem …
DateTime
The cmdlet appears in the list only because step 1 already loaded its module. In a brand-new session, -All lists only commands from loaded modules plus the ones it can find on disk.
Remove-Item Alias:\Get-ChildItem, Function:\Get-ChildItem Get-Command Get-ChildItem -All | Format-Table CommandType, Name, Source
CommandType Name Source
----------- ---- ------
Cmdlet Get-ChildItem Microsoft.PowerShell.Management
Alias: and Function: are drives exposed by providers (Lesson 4); Remove-Item works on them like on files.
New-LabData.ps1 -Path ./tmp/data 2>&1 | Select-Object -First 1 ./New-LabData.ps1 -Path ./tmp/data | Select-Object AccessLog
New-LabData.ps1: The term 'New-LabData.ps1' is not recognized as a name of a cmdlet, function, script file, or executable program.
AccessLog
---------
611
Clean up with Remove-Item -LiteralPath ./tmp/data -Recurse. In an interactive console, PowerShell also prints a suggestion telling you to type .\New-LabData.ps1 because it found the file in the current folder.
Case 1: a cleanup script that worked on Windows deleted nothing on Linux
Problem: ls $dir | Where-Object { $_.LastWriteTime -lt $cutoff } | Remove-Item -ErrorAction SilentlyContinue was moved from Windows to a Linux container. The job reported success and the disk kept filling up. Root cause: on Linux ls is /bin/ls; its output is plain strings, which have no LastWriteTime. $null -lt $cutoff is $true, so every name passed the filter, but the bare names were resolved against the current folder instead of $dir, every delete failed, and SilentlyContinue hid all the errors. Fix: use Get-ChildItem -LiteralPath $dir -File; never use aliases in scripts; never hide errors you have not read.
Case 2: an innocent helper function broke a build
Problem: A team's shared profile defined function Get-Content { … } to add colorized output. Build scripts that dot-sourced that profile produced ANSI escape codes inside generated JSON. Root cause: functions take precedence over cmdlets. Fix: never shadow built-in names; give helpers your own noun prefix (Show-ColorContent), and run builds with -NoProfile.
Case 3: curl behaves differently in two pipelines
Problem: The same deployment step returned an object in one agent and text in another. Root cause: one agent ran Windows PowerShell 5.1, where curl is an alias for Invoke-WebRequest; the other ran pwsh 7, where curl is the real curl. Fix: say what you mean: Invoke-RestMethod for objects, curl.exe for the native tool (Lesson 7).
Common errors and fixes
The term 'X' is not recognized as a name of a cmdlet, function, script file, or executable program
Cause: typo; module not installed for this edition; script in the current folder called without ./; executable not on PATH.
Get-Command X -All -ErrorAction Ignore Get-Module -ListAvailable *X* Test-Path ./X.ps1
Fix: use ./X.ps1; install the module (Lesson 4); add the folder to PATH or call the full path with &.
A command does something completely unexpected
Cause: an alias or function shadows the command you meant.
Get-Command name -All | Format-Table CommandType, Name, Source
Fix: call it module-qualified (Module\Command) or remove the shadowing alias/function.
Method invocation failed because [System.String] does not contain a method named …
Cause: you ran a native program (text output) but treated the result like objects — often ls/ps on Linux.
(Get-Command ls).CommandType
Fix: use the cmdlet: Get-ChildItem, Get-Process.
1. List every alias that points to Get-ChildItem.
Get-Alias -Definition Get-ChildItem
On Windows: dir, gci, ls. On Linux/macOS: dir, gci.
2. Count the cmdlets in the Microsoft.PowerShell.Utility module.
(Get-Command -Module Microsoft.PowerShell.Utility -CommandType Cmdlet).Count
Your team wants a cross-platform script that lists the 5 largest files in a folder. A draft uses ls -S | head -5. Review it.
This only works where ls and head are native Unix tools, returns text, and breaks on Windows (where ls is Get-ChildItem and -S is ambiguous). Use objects: Get-ChildItem -LiteralPath $Path -File | Sort-Object Length -Descending | Select-Object -First 5 Name, Length. It works the same everywhere and the result can be piped onward or exported.
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
Visual: the word “ls” splits into three cards: Alias, Function, Application.
Narration: one name can mean several things; PowerShell checks them in a fixed order.
Visual: a ladder Alias → Function → Cmdlet → External; a token climbs down and stops at the first match.
Narration: alias, then function, then cmdlet, then programs on PATH.
Visual: the same script on Windows (objects) and Linux (text) gives different results.
Narration: on Linux, ls is the real ls. Use full cmdlet names in scripts.
Visual: Get-Command -All output with the first row highlighted.
Narration: when in doubt, ask Get-Command -All.
Module 3 · Discovery: Get-Command, Get-Help and syntax diagrams
- Find commands by verb, noun, module or wildcard with
Get-Command. - Install help with
Update-Helpand read-Examples,-Parameter,-Full,-Onlineandabout_*topics. - Read a syntax diagram: parameter sets,
[[-Path] <string[]>](optional and positional),-LiteralPath <string[]>(mandatory), switches,[<CommonParameters>]. - Know that parameter names can be shortened while unambiguous, and why scripts should not do it.
What: the three discovery commands
| Question | Command | Example |
|---|---|---|
| Which command does X? | Get-Command | Get-Command -Noun *Service*, Get-Command *json* |
| How do I use it? | Get-Help | Get-Help Get-ChildItem -Examples |
| What did it give me? | Get-Member (Module 4) | Get-Process | Get-Member |
Why: help is not installed by default
PowerShell 7 ships with no full help content. Without it, Get-Help shows only the syntax generated from the cmdlet's metadata and a remark: “Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.” Run Update-Help -Scope CurrentUser once (it needs internet access; it may report errors for a few modules that publish no help — that is normal), or use -Online to open Microsoft Learn. The conceptual topics, such as about_Pipelines and about_Quoting_Rules, are also part of the downloaded help.
How: reading a syntax diagram
| Notation | Meaning | Example from Get-ChildItem |
|---|---|---|
[[-Path] <string[]>] | Optional; the name -Path itself is optional too, so it is positional (position 0) | Get-ChildItem ~/pslab |
[[-Filter] <string>] | Optional, positional (position 1) | Get-ChildItem ~/pslab *.csv |
-LiteralPath <string[]> | Not in brackets: mandatory in that parameter set, and must be named | Get-ChildItem -LiteralPath '[draft] notes.md' |
[-Recurse] | A switch: no value; present = true | -Recurse, or -Recurse:$false |
<string[]> | Accepts several values | -Path a.txt, b.txt |
{None | ReadOnly | …} | An enum: only these values | -Attributes Hidden |
[<CommonParameters>] | The common parameters every cmdlet and advanced function gets | -Verbose -ErrorAction -WarningAction -OutVariable -PipelineVariable … |
Each block of syntax is a parameter set: a valid combination. Get-ChildItem has two sets, Items (uses -Path) and LiteralItems (uses -LiteralPath); you cannot use both in one call. If the parameters you give fit no set, you get “Parameter set cannot be resolved using the specified named parameters.”
When: abbreviations and tab completion
Interactively you can shorten a parameter name while it is unambiguous (-Rec for -Recurse) and press Tab to complete commands, parameters, values and even property names. In scripts, write full names: a future version may add a parameter that makes your abbreviation ambiguous (-n fails on Get-ChildItem once a second parameter starts with “n”).
Update-Help. ② “Positional parameters are fine in scripts” — readability suffers; name them. ③ “-? is different from Get-Help” — Get-ChildItem -? is the same as Get-Help Get-ChildItem. ④ “Update-Help needs admin” — not with -Scope CurrentUser.Diagram: anatomy of one syntax line
Syntax diagram decoder
Pick a command line and step through how PowerShell matches each argument to a parameter of Get-ChildItem, and which parameter set it ends up in.
Command reference
| Command | Purpose | Notes |
|---|---|---|
Update-Help -Scope CurrentUser | Download help content | Once, then occasionally; -ErrorAction SilentlyContinue hides modules without help |
Get-Help X -Examples | Worked examples | Usually the fastest route |
Get-Help X -Parameter Path | One parameter: position, pipeline input, wildcards | -Parameter * for all |
Get-Help X -Online | Open the Microsoft Learn page | Works without local help |
Get-Help about_* | List conceptual topics | Get-Help about_Quoting_Rules |
Get-Command X -Syntax | Syntax only, no help needed | Generated from metadata |
(Get-Command X).ParameterSets.Name | Parameter set names | .Parameters.Keys for all parameters |
Show-Command X | GUI form for a command (Windows) | Handy for learning, not for scripts |
Get-Help Get-ChildItem # before Update-Help
NAME
Get-ChildItem
SYNTAX
Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>]
[-Recurse] [-Depth <uint>] [-Force] [-Name] [-Attributes {None | ReadOnly | Hidden | …}] … [<CommonParameters>]
Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] … [<CommonParameters>]
ALIASES
gci
ls
dir
REMARKS
Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
-- To download and install Help files for the module that includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type: "Get-Help Get-ChildItem -Online" or
go to https://go.microsoft.com/fwlink/?LinkID=2096492.
(Get-Command Get-ChildItem).ParameterSets.Name Get-Help Get-ChildItem -Parameter Filter
Items
LiteralItems
-Filter <string>
Required? false
Position? 1
Accept pipeline input? false
Parameter set name (All)
Aliases None
Dynamic? false
Accept wildcard characters? false
How to verify: “Position? 1” means the second unnamed argument binds here. “Accept wildcard characters? false” is about PowerShell wildcards; -Filter is passed to the provider, which applies its own matching (Module 6). Common mistake: using -Include without -Recurse or a wildcard path and getting nothing. Production use: read -Parameter help for “Accept pipeline input?” before you design a pipeline (Module 5).
Get-Verb | Measure-Object | Select-Object -ExpandProperty Count Get-Verb -Group Security | Format-Table Verb, AliasPrefix, Group
100 Verb AliasPrefix Group ---- ----------- ----- Block bl Security Grant gr Security Protect pt Security Revoke rk Security Unblock ul Security Unprotect up Security
Goal: Answer five questions using only the discovery commands — no web search. Environment: pwsh 7.6; internet access for Update-Help (optional). Cost: a few MB of help files in your user profile.
-Online later instead):
Update-Help -Scope CurrentUser -UICulture en-US -ErrorAction SilentlyContinue (Get-Help about_* | Measure-Object).Count
Before updating, only the about topics shipped with installed modules (such as Pester's) appear; afterwards there are well over a hundred.
Get-Command *json*
Expected: ConvertFrom-Json, ConvertTo-Json, Test-Json in Microsoft.PowerShell.Utility.
Get-Command Get-ChildItem -Syntax Get-ChildItem ~/pslab -File -Recurse -Depth 2 | Select-Object -First 3 FullName
Get-Help Get-Content -Parameter * | Where-Object pipelineInput -like '*ByPropertyName*' | Select-Object name, pipelineInput
Works with downloaded help. Without help, read the metadata directly — this is what Module 5 builds on:
(Get-Command Get-Content).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipelineByPropertyName -contains $true } |
Select-Object Name, @{ n = 'Aliases'; e = { $_.Aliases -join ',' } }
Name Aliases ---- ------- ReadCount TotalCount First,Head Tail Last Path LiteralPath PSPath,LP Credential
$ in single quotes?
Get-Help about_Quoting_Rules -ShowWindow # Windows GUI; or pipe to more / Select-String Get-Help about_Quoting_Rules | Select-String 'single-quoted' | Select-Object -First 3
Enable or Activate?
Get-Verb Enable, Activate
Enable is approved (Lifecycle group); Activate is not in the list, so Import-Module would warn about an unapproved verb (Lesson 4).
Case 1: a script broke after a module upgrade because of an abbreviation
Problem: A script called New-AzResourceGroup -N $name -L $loc. After a module update it failed with “Parameter cannot be processed because the parameter name 'N' is ambiguous.” Root cause: abbreviations are resolved at run time against the current parameter list. Fix: full parameter names in scripts; PSScriptAnalyzer (Lesson 8) can flag positional and abbreviated usage in code review.
Case 2: build agents with no internet and no help
Problem: Engineers on locked-down jump hosts could not read examples. Fix: Save-Help -DestinationPath \\share\pshelp on a connected machine, then Update-Help -SourcePath \\share\pshelp -Scope CurrentUser on the isolated hosts.
Common errors and fixes
Parameter set cannot be resolved using the specified named parameters
Cause: you mixed parameters from different sets (for example -Path and -LiteralPath).
Get-Command Get-ChildItem -Syntax
Fix: pick parameters that appear together in one syntax block.
Parameter cannot be processed because the parameter name 'F' is ambiguous. Possible matches include: -Filter -Force.
Cause: an abbreviation matches several parameters.
Fix: type more characters or the full name; use Tab completion interactively.
Update-Help: Failed to update Help for the module(s) …
Cause: some modules publish no updatable help, or there is no internet access; in 5.1 the default scope needs administrator rights.
Update-Help -Scope CurrentUser -ErrorAction SilentlyContinue
Fix: ignore errors for modules without help; for offline machines use Save-Help + -SourcePath.
1. Show only the examples for Sort-Object, online if help is not installed.
Get-Help Sort-Object -Examples Get-Help Sort-Object -Online
2. List the parameter sets of Select-Object and count them.
(Get-Command Select-Object).ParameterSets.Name (Get-Command Select-Object).ParameterSets.Count # 4 in 7.6
A new team member asks you how to remove a Windows service with PowerShell. Without searching the web, how would you find the answer?
Guess the verb and noun: Get-Command -Noun Service shows Remove-Service (PowerShell 6+). Then Get-Help Remove-Service -Examples and -Parameter Name. Before running it for real, check whether it supports -WhatIf (Get-Command Remove-Service -Syntax); it does, so try Remove-Service -Name demo -WhatIf first (Lesson 5).
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
Visual: three keys labelled Get-Command, Get-Help, Get-Member unlock three doors.
Narration: find it, learn it, inspect what it returns.
Visual: a syntax line; brackets light up one by one with labels “optional”, “positional”, “mandatory”, “switch”.
Narration: brackets mean optional; double brackets mean you can even omit the name.
Visual: Get-Help with the “partial help” remark, then Update-Help, then rich examples.
Narration: help is downloaded separately. Update it once and the examples appear.
Module 4 · Objects, Get-Member and the formatting system
- Use
Get-Memberto list an object's type name, properties and methods. - Access properties and call methods:
$f.Length,$f.LastWriteTimeUtc.ToString('o'),(Get-Date).AddDays(-7). - Explain the difference between a .NET object (FileInfo) and a PSCustomObject (from
Import-Csv), and why CSV values are strings. - Explain how
Out-Defaultand format views choose table or list, and why Format-Table in the middle of a pipeline produces garbage.
What: an object is data with a type
In Bash, ls -l prints text and you cut columns out of it. In PowerShell, Get-Item ./data/access.log returns a System.IO.FileInfo object. Its properties (Name, Length, LastWriteTime, Directory) are typed values — Length is a number, LastWriteTime is a DateTime — and its methods (CopyTo(), Delete()) are actions. What you see on screen is only one possible rendering of it.
| Member type | Meaning | Example |
|---|---|---|
| Property | Data defined by the .NET type | FileInfo.Length |
| Method | An action you call with () | $d.AddDays(-1) |
| NoteProperty | A property PowerShell attached (no type behind it) | Every column of Import-Csv |
| ScriptProperty / AliasProperty | Computed or renamed properties added by PowerShell's type system | Process.WS → WorkingSet64 |
| CodeProperty, PropertySet, Event | Less common extended members | FileInfo.Mode, FileInfo.ResolvedTarget, Process.PSResources |
Why: types decide behavior
Import-Csv cannot know types, so every value is a string. Sorting "9" and "10" as strings puts 10 first; [bool]'false' is $true because any non-empty string is true. JSON keeps numbers and booleans (Lesson 2). When in doubt, ask Get-Member or .GetType().
How: the formatting system
- Every pipeline you type at the prompt ends with an invisible
Out-Default. - Out-Default looks up a view for the object's type name in the formatting data (
*.format.ps1xml, compiled into the engine for built-in types). FileInfo has a table view withMode, LastWriteTime, Length, Name. - No view? It uses the default display property set if there is one, otherwise all properties: table if ≤ 4 properties, list if 5 or more.
Format-Table/Format-List/Format-Wideconvert objects into format records (FormatStartData,GroupStartData,FormatEntryData…) that onlyOut-*cmdlets understand.
When: “filter left, format right”
Select, sort and filter while you still have real objects; format only as the last step, and only for human eyes. Anything that feeds another command, a file (Export-Csv, ConvertTo-Json) or a variable must receive objects, not format records. Use Select-Object (keeps objects) instead of Format-Table (destroys them) to choose columns.
Format-List * or Get-Member shows everything. ② “Format-Table chooses columns, like Select-Object” — it produces format records; | Export-Csv after it writes nonsense. ③ “CSV columns keep their type” — they are strings. ④ “Write-Host output can be captured” — it goes to the host/information stream, not to the pipeline (Module 8).Diagram: objects stay objects until Out-Default
Object vs text: what travels down the pipe?
Compare the same task in Bash and in PowerShell, and see what a Format cmdlet in the middle does to the data.
Command reference
| Command | Purpose | Notes |
|---|---|---|
X | Get-Member | Type name and members of each distinct type in the input | -MemberType Property, -Name *Time* |
$x.GetType().FullName | Exact .NET type | Arrays report System.Object[] |
X | Format-List * | Every property and value | For exploration only |
X | Format-Table Name, Length -AutoSize | Choose columns for display | Last in the pipeline |
[pscustomobject]@{ Name = 'a'; Size = 1 } | Create your own object | Property order is kept |
X | Out-String -Width 200 | Render to text (for logs or emails) | Use rarely; prefer objects |
$FormatEnumerationLimit | How many collection items to show (default 4) | Explains “{a, b, c, d…}” |
Set-Location ~/pslab $s = Import-Csv ./data/servers.csv $s.GetType().FullName; $s[0].GetType().FullName; $s.Count $s[0] | Get-Member
System.Object[] System.Management.Automation.PSCustomObject 12 TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Env NoteProperty string Env=dev IP NoteProperty string IP=10.10.1.21 Monitored NoteProperty string Monitored=true Name NoteProperty string Name=web-01 Region NoteProperty string Region=canadacentral Role NoteProperty string Role=web
How to verify: every NoteProperty is string — including Monitored. Common mistake: Where-Object Monitored treats "false" as true (Module 6). Production use: convert types once, right after import: [bool]::Parse($_.Monitored), [int]$_.Port, [ipaddress]$_.IP.
$f = Get-Item ./data/access.log $f.GetType().FullName; $f.Length; $f.Extension $f | Get-Member -MemberType Property | Select-Object -First 6 Name, MemberType, Definition
System.IO.FileInfo
80646
.log
Name MemberType Definition
---- ---------- ----------
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
DirectoryName Property string DirectoryName {get;}
Exists Property bool Exists {get;}
# Anti-pattern vs correct order Get-ChildItem ./data -File | Format-Table Name, Length | Sort-Object Length Get-ChildItem ./data -File | Sort-Object Length | Format-Table Name, Length
Name Length ---- ------ access.log 80646 inventory.json 1599 opskit.config.psd1 777 servers.csv 600 Name Length ---- ------ servers.csv 600 opskit.config.psd1 777 inventory.json 1599 access.log 80646
Get-Item ./data/servers.csv | Format-Table | Get-Member | Select-Object -ExpandProperty TypeName -Unique
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
Goal: Inspect three kinds of objects and build your own. Environment: pwsh 7.6 in ~/pslab. Cost: none.
data and print its age in minutes using its properties and methods.
$newest = Get-ChildItem ./data -File -Recurse -Force | Sort-Object LastWriteTimeUtc | Select-Object -Last 1 $newest.Name [int]((Get-Date).ToUniversalTime() - $newest.LastWriteTimeUtc).TotalMinutes
Subtracting two DateTime values gives a TimeSpan object with TotalMinutes, Days … — no date parsing needed.
$s = Import-Csv ./data/servers.csv $s[0].IP.GetType().Name '10' -gt '9' # string comparison [int]'10' -gt [int]'9'
String False True
$report = foreach ($file in Get-ChildItem ./data -File) {
[pscustomobject]@{
Name = $file.Name
SizeKB = [math]::Round($file.Length / 1KB, 1)
Lines = (Get-Content -LiteralPath $file.FullName).Count
Modified = $file.LastWriteTimeUtc.ToString('yyyy-MM-dd')
}
}
$report | Sort-Object SizeKB -Descending | Format-Table
Name SizeKB Lines Modified ---- ------ ----- -------- access.log 78.80 611 2026-11-24 inventory.json 1.60 14 2026-11-24 opskit.config.psd1 0.80 14 2026-11-24 servers.csv 0.60 13 2026-11-24
1KB is a numeric literal (1024). foreach collects every object the loop body outputs into $report.
Format-List *.
Get-Item ./data/servers.csv Get-Item ./data/servers.csv | Format-List *
The first uses FileInfo's table view (Mode, LastWriteTime, Length, Name); the second lists every property (about 30, including PowerShell-added ones such as PSPath and BaseName).
Case 1: a CSV report full of “ClassId2e4f51ef21dd47e99d3c952918aff9cd”
Problem: A weekly disk report was produced with Get-CimInstance Win32_LogicalDisk | Format-Table DeviceID, FreeSpace | Export-Csv disks.csv. The CSV contained columns named ClassId2e4f51ef… and no data. Root cause: Format-Table output format records. Fix: Select-Object DeviceID, FreeSpace | Export-Csv -NoTypeInformation (the switch is the default in 7 and harmless to include for 5.1).
Case 2: a monitoring script alerted on healthy servers
Problem: Import-Csv servers.csv | Where-Object { $_.Monitored } | … checked every server, including those marked false. Root cause: the non-empty string "false" is truthy. Fix: compare explicitly ($_.Monitored -eq 'true') or convert once ([bool]::Parse()), or switch the inventory to JSON, which keeps booleans.
Case 3: truncated values in a log email
Problem: An emailed report showed {web, api, db, edge…}. Root cause: $FormatEnumerationLimit (default 4) and the console width used by Out-String. Fix: join collections yourself ($_.Roles -join ', ') or send structured data (CSV/JSON attachment) instead of formatted text.
Common errors and fixes
out-lineoutput: The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence
Cause: two Format-* cmdlets in one pipeline, or format records passed to a command that expected objects.
Fix: keep exactly one Format-* at the very end; use Select-Object to choose properties earlier.
A property I can see in Get-Member is empty in the table
Cause: the default view shows selected columns only, or the column was truncated by the console width.
X | Format-List Name, TheProperty X | Select-Object Name, TheProperty | Format-Table -Wrap
Sorting puts 10 before 9 / comparison gives the wrong answer
Cause: the values are strings (CSV, text output).
$x | Get-Member -Name Port
Fix: Sort-Object { [int]$_.Port } or convert when importing.
1. Show only the properties of a Process object whose name contains “Memory”.
Get-Process -Id $PID | Get-Member -MemberType Properties -Name *Memory*
$PID is the current PowerShell process. Properties (plural) includes NoteProperty, ScriptProperty and AliasProperty.
2. Create an object describing your PowerShell session (edition, version, host, OS) and export it as JSON.
[pscustomobject]@{
Edition = $PSVersionTable.PSEdition
Version = "$($PSVersionTable.PSVersion)"
Host = $Host.Name
OS = $PSVersionTable.OS
} | ConvertTo-JsonA colleague's script ends with | Format-Table -AutoSize | Out-File report.txt, and a second script parses report.txt with regular expressions to build alerts. What would you change?
The first script throws away the objects and the second rebuilds them from text — two places to break (column widths, truncation, culture-specific number formats). Have the first script output objects and save them with Export-Csv or ConvertTo-Json | Set-Content; the second script reads them back with Import-Csv / ConvertFrom-Json. Keep Format-Table only for the human-readable copy.
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
Visual: Bash pipe carrying strips of text; PowerShell pipe carrying labelled boxes (Name, Length, LastWriteTime).
Narration: Bash passes text; PowerShell passes objects with typed properties.
Visual: Get-Member opens one box and lists its contents.
Narration: Get-Member tells you exactly what you are holding.
Visual: a Format-Table stage in the middle turns boxes into “paint”, and the next stage cannot read them.
Narration: formatting is paint for your screen. Do it last.
Module 5 · The Pipeline: streaming and parameter binding
A | B works before you run it- Describe streaming: every command's
beginruns first, then objects flow one by one throughprocess, thenend. - Predict binding: ByValue (the whole object, matched by type, without then with coercion) before ByPropertyName (a property whose name — or alias — matches a parameter).
- Use
Get-Help -Parameter/ the command metadata andTrace-Command -Name ParameterBindingto prove which parameter received the object. - Fix “The input object cannot be bound …” by reshaping objects with
Select-Objectcalculated properties or by usingForEach-Object.
What: a pipeline is a chain of command processors
For A | B | C, PowerShell creates a processor for each command, binds their named and positional arguments, calls every BeginProcessing, then pushes each object that A writes into B's ProcessRecord, whose output goes into C, and so on. Finally every EndProcessing runs. Sort-Object and Group-Object must collect everything and emit in end; Where-Object, Select-Object -First and ForEach-Object stream.
Why: binding is per object, by rules you can read
Each parameter declares in its metadata whether it accepts pipeline input ByValue, ByPropertyName, both or neither. For every incoming object the binder:
- Tries ByValue without coercion: is the object already the parameter's type (FileInfo for
-InputObject [FileInfo[]])? - Tries ByPropertyName without coercion: does the object have a property named like the parameter or one of its aliases?
- Tries ByValue with coercion: can it be converted (anything converts to
[string])? - Tries ByPropertyName with coercion.
- Nothing matched → “The input object cannot be bound to any parameters for the command …”.
How: three real examples
| Pipeline | Parameter that binds | Why |
|---|---|---|
Get-Item ./data/servers.csv | Get-Content | -LiteralPath | FileInfo has a PSPath property; PSPath is an alias of -LiteralPath (ByPropertyName). That is why piping files never has wildcard problems. |
'./data/servers.csv' | Get-ChildItem | -Path | A string; -Path [string[]] accepts ByValue. |
Get-Process -Id $PID | Stop-Process | -InputObject | A Process object matches [Process[]] ByValue. |
'pwsh' | Get-Process | none — error | -Name accepts only ByPropertyName; a string has no Name property. |
[pscustomobject]@{Name='pwsh'} | Get-Process | -Name | Now the object has a Name property. |
When: coercion surprises
Because almost anything converts to a string, ByValue-with-coercion can bind things you did not mean: Get-Date | Get-ChildItem converts the date to text and fails with “Cannot find drive. A drive with the name '11/24/2026 8' does not exist.” And objects that match nothing cause errors per object — piping Import-Csv servers.csv into Get-Content fails because a server row has no Path, LiteralPath or PSPath property.
$_ works everywhere” — only inside script blocks run per object (Where-Object, ForEach-Object, calculated properties, delay-bind script blocks).Diagram: one object through the binder
Diagram: streaming order
Core animation: pipeline parameter binding
Choose a pipeline and step through the binder's four attempts for the first object. Green = bound, yellow = tried and skipped, red = failed. Every outcome shown here was reproduced on PowerShell 7.6.10.
Trace-Command -Name ParameterBinding prints: BIND NAMED cmd line args, BIND POSITIONAL cmd line args, MANDATORY PARAMETER CHECK, CALLING BeginProcessing, then for each object BIND PIPELINE object to parameters with “NO COERCION” attempts before “WITH COERCION” attempts, and finally CALLING EndProcessing.Command reference
| Command | Purpose | Notes |
|---|---|---|
Get-Help B -Parameter * | “Accept pipeline input?” per parameter | Needs downloaded help |
(Get-Command B).Parameters.Values | Same information from metadata | See the Lab |
Trace-Command -Name ParameterBinding -Expression { A | B } -PSHost | Show every binding decision | Very verbose; read the “BIND PIPELINE” part |
A | Select-Object @{n='Path';e={$_.FullName}} | B | Rename a property so it binds | Calculated property (Module 6) |
A | ForEach-Object { B -Param $_.X } | Bind explicitly per object | Always works; slightly slower |
-PipelineVariable v | Keep an earlier stage's object available as $v later | Common parameter |
(Get-Command Get-Content).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipeline -contains $true -or $_.Attributes.ValueFromPipelineByPropertyName -contains $true } |
ForEach-Object { '{0} [{1}] ByValue={2} ByPropertyName={3} Aliases={4}' -f $_.Name, $_.ParameterType.Name,
($_.Attributes.ValueFromPipeline -contains $true), ($_.Attributes.ValueFromPipelineByPropertyName -contains $true), ($_.Aliases -join ',') }
ReadCount [Int64] ByValue=False ByPropertyName=True Aliases= TotalCount [Int64] ByValue=False ByPropertyName=True Aliases=First,Head Tail [Int32] ByValue=False ByPropertyName=True Aliases=Last Path [String[]] ByValue=False ByPropertyName=True Aliases= LiteralPath [String[]] ByValue=False ByPropertyName=True Aliases=PSPath,LP Credential [PSCredential] ByValue=False ByPropertyName=True Aliases=
How to verify: Get-Content has no ByValue parameter at all, so a plain string piped into it can only bind by property name — and a string has no Path property. That is why 'a.txt' | Get-Content fails while Get-Item a.txt | Get-Content works. Common mistake: assuming “it takes a path, so I can pipe a path”. Production use: when designing your own functions (Lesson 3), accept ValueFromPipelineByPropertyName with the aliases PSPath/FullName so files pipe in naturally.
Trace-Command -Name ParameterBinding -PSHost -Expression {
Get-Item ./data/servers.csv | Get-Content -TotalCount 1
}
BIND NAMED cmd line args [Get-Item]
BIND POSITIONAL cmd line args [Get-Item]
BIND arg [./data/servers.csv] to parameter [Path]
BIND NAMED cmd line args [Get-Content]
BIND arg [1] to parameter [TotalCount]
COERCE arg to [System.Int64]
MANDATORY PARAMETER CHECK on cmdlet [Get-Content]
CALLING BeginProcessing
CALLING BeginProcessing
CALLING ProcessRecord
BIND PIPELINE object to parameters: [Get-Content]
PIPELINE object TYPE = [System.IO.FileInfo]
Parameter [Path] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
Parameter [LiteralPath] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
BIND arg [Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv] to parameter [LiteralPath]
BIND arg [System.String[]] to param [LiteralPath] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [Get-Content]
CALLING ProcessRecord
CALLING EndProcessing
CALLING EndProcessing
Name,Env,Region,IP,Role,Monitored
Goal: Predict, then prove, how objects bind. Environment: pwsh 7.6 in ~/pslab. Cost: none (the only “stop” runs with -WhatIf).
'pwsh' | Get-Process
[pscustomobject]@{ Name = 'pwsh' } | Get-Process | Select-Object -First 1 -ExpandProperty ProcessName
'./data/servers.csv' | Get-ChildItem | ForEach-Object Name
[pscustomobject]@{ Path = './data/servers.csv' } | Get-Content -TotalCount 1
Get-Process: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. pwsh servers.csv Name,Env,Region,IP,Role,Monitored
ForEach-Object stages interleave.
1..3 | ForEach-Object { Write-Host "A $_"; $_ } | ForEach-Object { Write-Host " B $_" }
1..3 | ForEach-Object -Begin { 'begin' } -Process { "process $_" } -End { 'end' }
A 1 B 1 A 2 B 2 A 3 B 3 begin process 1 process 2 process 3 end
Name property that Test-Connection-style commands could use, or into paths for Get-Content.
Import-Csv ./data/servers.csv | Select-Object -First 1 | Get-Content -ErrorAction Stop # fails
Get-ChildItem ./data -File |
Select-Object @{ n = 'LiteralPath'; e = { $_.FullName } }, Name |
Select-Object -First 1 |
Get-Content -TotalCount 1
Get-Content: The input object cannot be bound to any parameters for the command … 203.0.113.7 - - [24/Nov/2026:10:00:01 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"
Get-ChildItem ./data -File -PipelineVariable file |
Select-Object -First 2 |
ForEach-Object { '{0} is {1} bytes' -f $file.Name, $file.Length }
access.log is 80646 bytes inventory.json is 1599 bytes
Trace-Command example from the Commands tab and find the line BIND arg [...] to parameter [LiteralPath].Case 1: a service-restart job that “could not find” any service
Problem: An on-call runbook did Import-Csv services.csv | Get-Service | Restart-Service. The CSV header was Service. Every row failed with “Cannot find any service with service name '@{Service=Winmgmt}'.” Root cause: Get-Service -Name accepts pipeline input ByValue and ByPropertyName (alias ServiceName). No property was called Name or ServiceName, so the binder fell back to ByValue with coercion and turned the whole row into the string @{Service=Winmgmt}. Fix: rename the column to Name or ServiceName, or be explicit: ForEach-Object { Restart-Service -Name $_.Service -WhatIf }. Both behaviors were reproduced on 7.6.10 with the Winmgmt service (read-only Get-Service, Windows).
Case 2: memory blow-up while sorting a 20 GB log
Problem: Get-Content huge.log | Sort-Object | Select-Object -First 10 exhausted memory. Root cause: Sort-Object must hold every line before it can output the first one. Fix: filter early (Select-String, Where-Object) so fewer objects reach the blocking stage; use -ReadCount for speed; or aggregate with a hashtable in a streaming ForEach-Object (Lesson 2).
Case 3: “works in the console, fails with a date in the path”
Problem: A helper piped a [datetime] into Get-ChildItem by mistake; the error mentioned a missing drive named after the date. Root cause: ByValue-with-coercion turned the date into a string path. Fix: build paths explicitly (Join-Path $root (Get-Date -Format 'yyyy-MM-dd')).
Common errors and fixes
The input object cannot be bound to any parameters for the command …
Cause: no parameter accepts this object ByValue, and it has no property matching a ByPropertyName parameter or alias.
$obj | Get-Member
(Get-Command B).Parameters.Values | Where-Object { $_.Attributes.ValueFromPipelineByPropertyName -contains $true } | Select-Object Name, Aliases
Fix: rename with a calculated property, or use ForEach-Object { B -Param $_.X }.
Cannot find drive. A drive with the name '…' does not exist.
Cause: a non-path object was coerced to a string path (a date, a hashtable), or a path contains :.
Fix: check what you piped with Get-Member; build paths with Join-Path.
The command waits forever after a pipeline / nothing appears until the end
Cause: a blocking cmdlet (Sort-Object, Group-Object, Measure-Object) is collecting a large input.
Fix: filter before the blocking stage; check with a small Select-Object -First sample.
1. List the parameters of Stop-Process that accept pipeline input and how.
(Get-Command Stop-Process).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipeline -contains $true -or $_.Attributes.ValueFromPipelineByPropertyName -contains $true } |
Select-Object Name, @{ n = 'ByValue'; e = { $_.Attributes.ValueFromPipeline -contains $true } }Actual (7.6.10): Name (ByPropertyName), Id (ByPropertyName), InputObject (ByValue).
2. Read the first line of every .csv and .json file in ./data with one pipeline.
Get-ChildItem ./data -File -Include *.csv, *.json -Recurse | Get-Content -TotalCount 1
-Include needs -Recurse or a wildcard in the path to have an effect.
Why does Get-ChildItem *.log | Remove-Item safely delete a file named app[1].log, but Remove-Item app[1].log does not find it?
In the pipeline, the FileInfo object binds to -LiteralPath through its PSPath property, so brackets are taken literally. Typed on the command line, app[1].log goes to -Path, where [1] is a wildcard character class matching app1.log. Use -LiteralPath 'app[1].log' (Module 7).
Verified teaching videos
Official documentation
- about_Pipelines (includes “Investigating pipeline errors” with Trace-Command) · Trace-Command · PowerShell 101: One-liners and the pipeline
Video storyboard (about 90 seconds)
Visual: objects ride a conveyor belt one at a time from A to B.
Narration: objects are passed one at a time, not all at once.
Visual: at B's door, a guard checks the object's type (ByValue) and then its name badge properties (ByPropertyName).
Narration: by value first, then by property name — and property aliases count.
Visual: a string 'pwsh' is turned away by Get-Process; a box labelled Name=pwsh is let in.
Narration: if it doesn't bind, give the object the property the command expects.
Module 6 · Filtering and shaping: Where, Select, Sort, Group, Measure
- Filter with
Where-Objectin both forms (comparison statement and script block) and know when each is needed. - Choose and compute columns with
Select-Object:-First/-Last/-Skip,-Unique,-ExpandProperty, calculated properties. - Sort on several keys, group and count with
Sort-Object,Group-Object,Measure-Object. - Apply filter left: use a command's own filter parameters (
-Filter,-Name) beforeWhere-Object, and know the faster.Where()method.
What: the five shaping cmdlets
| Cmdlet | Alias | Bash equivalent | Streams? |
|---|---|---|---|
Where-Object | ?, where | grep, awk '$3 > 5' | Yes |
Select-Object | select | cut, head, tail | Yes (-Last and -Unique must collect) |
Sort-Object | sort (Windows) | sort | No |
Group-Object | group | sort | uniq -c | No |
Measure-Object | measure | wc -l, awk '{s+=$1}' | No |
Why: two syntaxes for Where-Object
Comparison statement (PowerShell 3+): Where-Object Env -eq 'prod' — short, one condition. Script block: Where-Object { $_.Env -eq 'prod' -and $_.Role -like '*web*' } — any expression; $_ (or $PSItem) is the current object. A bare property, Where-Object Monitored, tests truthiness — dangerous with CSV strings, where 'false' is true.
How: calculated properties
A hashtable with Name (or n/Label) and Expression (or e) adds a computed column; it works in Select-Object, Sort-Object, Group-Object and Format-Table:
Select-Object Name, @{ Name = 'SizeKB'; Expression = { [math]::Round($_.Length / 1KB, 1) } }
When: filter left
| Slower | Faster | Why |
|---|---|---|
Get-ChildItem -Recurse | Where-Object Extension -eq '.log' | Get-ChildItem -Recurse -Filter *.log | The provider filters before objects are created |
Get-Process | Where-Object Name -eq pwsh | Get-Process -Name pwsh | The cmdlet looks up directly |
1..100000 | Where-Object { $_ % 2 } (≈ 1 s) | (1..100000).Where({ $_ % 2 }) (≈ 0.2 s) | The method avoids per-object pipeline overhead (measured on the lab machine) |
For remote and cloud commands, filter left matters even more: Get-AzVM -ResourceGroupName rg asks the server for less data; | Where-Object filters only after everything was downloaded (Lesson 7).
Select-Object Name returns strings” — it returns objects with one property; use -ExpandProperty Name or .Name for strings. ② “Sort-Object sorts numbers in CSV correctly” — strings sort as text; use { [int]$_.X }. ③ “-Unique is case-insensitive” — Select-Object -Unique is case-sensitive unless you add -CaseInsensitive (7.4+); Sort-Object -Unique is case-insensitive. ④ “Where-Object Monitored tests the value” — it tests truthiness.Diagram: one report, stage by stage
Pipeline stage-by-stage data view
Step through a report on servers.csv and watch how many objects survive each stage and what their properties are.
Command reference
| Command | Purpose | Notes |
|---|---|---|
Where-Object Env -eq prod | Simple filter | Operators: -eq -ne -gt -lt -like -match -in -contains (+ c/i prefixes) |
Where-Object { … -and … } | Complex filter | $_ = current object |
Select-Object -First 5 Name, IP | Columns and rows | -Skip, -Last, -Unique |
Select-Object -ExpandProperty Name | Values instead of objects | Same as (…).Name for most cases |
Sort-Object Env, @{e='Name';Descending=$true} | Multi-key sort | Per-key direction with a hashtable |
Group-Object Env -NoElement | Counts per value | Without -NoElement, .Group holds the objects |
Measure-Object Length -Sum -Average -Maximum | Statistics | -Line -Word -Character for text |
(…).Where({ }, 'First', 3) | Fast in-memory filter | Modes: First, Last, SkipUntil, Until, Split |
$s = Import-Csv ./data/servers.csv $s | Where-Object Env -eq 'prod' | Select-Object Name, IP, Role $s | Group-Object Env -NoElement | Sort-Object Count -Descending
Name IP Role
---- -- ----
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
db-01 10.30.1.44 db
bastion-01 10.30.2.10 bastion
Count Name
----- ----
6 prod
3 dev
3 staging
($s | Where-Object Monitored).Count # truthiness of a string
($s | Where-Object { $_.Monitored -eq 'true' }).Count # explicit comparison
[bool]'false'
12 8 True
How to verify: 12 ≠ 8 — four servers are "false", yet the first filter kept them. Common mistake: trusting truthiness for CSV data. Production use: convert at the edge: Import-Csv … | Select-Object *, @{n='IsMonitored';e={ $_.Monitored -eq 'true' }} -ExcludeProperty Monitored.
$s | Select-Object Name, Env, @{ Name = 'Fqdn'; Expression = { '{0}.{1}.example.com' -f $_.Name, $_.Env } } -First 3
(Select-String -Path ./data/access.log -Pattern '" 5\d\d ').Count
(Select-String -Path ./data/access.log -Pattern ' 5\d\d ').Count
Name Env Fqdn ---- --- ---- web-01 dev web-01.dev.example.com api-01 dev api-01.dev.example.com db-01 dev db-01.dev.example.com 20 37
The second pattern also matches byte counts such as 526 after a 200 status — anchor your text patterns. Lesson 2 parses each log line into an object with a regex so that the status becomes a number you can compare.
Goal: Build a server inventory report and a quick log summary without any text cutting. Environment: pwsh 7.6 in ~/pslab. Cost: none.
Import-Csv ./data/servers.csv |
Where-Object { $_.Monitored -eq 'true' } |
Group-Object Env |
Sort-Object Count -Descending |
Select-Object Name, Count, @{ n = 'Servers'; e = { ($_.Group.Name | Sort-Object) -join ', ' } }
Name Count Servers ---- ----- ------- prod 4 api-01, edge-01, web-01, web-02 dev 2 api-01, web-01 staging 2 api-01, web-01
Import-Csv ./data/servers.csv | Where-Object Role -like '*,*' | Select-Object Name, Role (Get-Content ./data/servers.csv)[10] -split ',' # naive split: 7 fields instead of 6
Import-Csv ./data/servers.csv | Select-Object -ExpandProperty Name | Sort-Object -Unique (Import-Csv ./data/servers.csv).Name | Sort-Object -Unique (Import-Csv ./data/servers.csv | Group-Object Name).Name
Get-ChildItem ./data/files -File | Measure-Object Length -Sum -Average -Maximum Get-ChildItem ./data/files -File -Recurse -Force | Measure-Object | Select-Object -ExpandProperty Count
Count : 11 Average : 8.18181818181818 Sum : 90 Maximum : 9 Minimum : StandardDeviation : Property : Length 12
(Measure-Command { 1..100000 | Where-Object { $_ % 2 } }).TotalMilliseconds
(Measure-Command { (1..100000).Where({ $_ % 2 }) }).TotalMilliseconds
On the lab machine: about 990 ms vs 210 ms. Your numbers will differ; the ratio is what matters.
Case 1: a nightly report took 40 minutes
Problem: Get-ChildItem \\fileserver\share -Recurse | Where-Object Extension -eq '.bak' ran for 40 minutes. Root cause: every file on the share became a FileInfo object before being thrown away. Fix: -Filter *.bak (the file system API filters on the server side) cut it to a few minutes; adding -File and -Depth limits cut it further.
Case 2: alerts for “10 errors” when there were 100
Problem: A script picked the top error code with Sort-Object Count after Import-Csv of a summary file. Root cause: Count was a string, so "9" sorted after "100". Fix: Sort-Object { [int]$_.Count } -Descending, or keep summaries in JSON.
Common errors and fixes
Where-Object returns nothing although matching data exists
Cause: wrong property name (no error is raised for a missing property), type mismatch, or case-sensitive operator.
$data | Select-Object -First 1 | Get-Member Set-StrictMode -Version Latest # makes some missing-property mistakes visible (Lesson 5)
Select-Object shows @{Name=web-01} instead of web-01
Cause: you have objects with one property, then put them in a string.
Fix: -ExpandProperty Name or $x.Name.
Measure-Object : Input object "…" is not numeric
Cause: the property holds text that cannot be converted, or empty values.
Fix: Where-Object { $_.Bytes -as [int] -ne $null } first, or convert with a calculated property.
1. Show the three largest files under ./data (recursively) with size in KB.
Get-ChildItem ./data -File -Recurse -Force |
Sort-Object Length -Descending |
Select-Object -First 3 Name, @{ n = 'KB'; e = { [math]::Round($_.Length / 1KB, 2) } }2. Count servers per region, but only in prod.
Import-Csv ./data/servers.csv | Where-Object Env -eq prod | Group-Object Region -NoElement
Actual (7.6.10): ca-central-1 2, canadacentral 4 (Group-Object sorts the groups by name).
A teammate writes Get-ADUser -Filter * | Where-Object Department -eq 'Sales' in a domain with 200,000 users. What is wrong, and what is better?
It downloads every user from the domain controller and filters locally — slow and heavy for the DC. Filter left on the server: Get-ADUser -Filter "Department -eq 'Sales'" -Properties Department. The same principle applies to Az, Graph and AWS cmdlets: use their server-side filter parameters, and keep Where-Object for what the server cannot filter.
Verified teaching videos
Official documentation
Video storyboard (about 90 seconds)
Visual: a Bash pipeline full of column numbers next to a PowerShell pipeline with property names.
Narration: name the property; forget column numbers.
Visual: the 12 → 8 drop when Monitored is compared explicitly; a red flag on '[bool]'false''.
Narration: CSV values are text. Compare explicitly.
Visual: a funnel at the source (–Filter) vs a sieve at the end (Where-Object).
Narration: filter left, format right.
Module 7 · Parsing modes, quoting, escaping and wildcards
- Predict expression mode vs argument mode: why
2+3prints 5 butWrite-Output 2+3prints2+3. - Choose single quotes (literal), double quotes (expand
$varand$( )) and here-strings; know that only$nameis expanded, not$obj.Property. - Use the backtick escape (
`t,`n,`$),--(end of parameters) and--%(stop parsing) correctly. - Handle names with
[ ],$,',`, a leading-,#and&using-LiteralPathand proper quoting.
What: two parsing modes
| Mode | Starts when the token begins with | Behaves like | Example |
|---|---|---|---|
| Expression | a number, a quote, $, (, @, [, an operator | a programming language: operators work, bare words are errors | 2+3 → 5; 'a' * 3 → aaa |
| Argument | a command name, then each argument | a shell: bare words are strings, -x is a parameter name | Write-Output 2+3 → 2+3 |
Inside argument mode you return to expression mode with parentheses ( ), a subexpression $( ) or an array subexpression @( ): Write-Output (2+3) prints 5. A variable is expanded in argument mode, but $s.Count as an argument is read as the variable followed by the text .Count only inside double-quoted strings — as a bare argument, member access works.
Why: quoting decides what is expanded
| Form | Variables $x | Subexpressions $( ) | Backtick escapes | Use for |
|---|---|---|---|---|
'single' | No | No | No (write '' for a quote) | Paths, regexes, anything literal — the default choice |
"double" | Yes, simple names only | Yes | Yes: `t `n `$ `" | Messages that include values |
@' … '@ | No | No | No | Literal multi-line text (scripts, JSON templates) |
@" … "@ | Yes | Yes | Yes | Multi-line text with values |
The most common bug: "Count: $s.Count" expands $s (the whole array, joined with spaces) and then appends the literal text .Count. Write "Count: $($s.Count)". The same applies to indexes: "$a[0]" → whole array + [0].
How: the escape character is the backtick
PowerShell's escape character is ` (not \, which is an ordinary path character on Windows). Inside double quotes: `n newline, `t tab, `$ literal dollar, `" literal quote, `e escape (ANSI). At the end of a line, a backtick continues the command on the next line — fragile, because a trailing space breaks it; prefer splatting (Lesson 3) or breaking after |, , or {.
When: wildcards, -LiteralPath and special arguments
-Pathparameters treat* ? [ ]as wildcards.[draft] notes.mdmeans “one of d, r, a, f, t, followed by ‘ notes.md’” and matches nothing. Use-LiteralPath, or escape with backticks ([WildcardPattern]::Escape()returns`[draft`] notes.md).- An argument that starts with
-looks like a parameter name:Get-Content -WhatIf.txtfails. Use-LiteralPath ./-WhatIf.txt, a./prefix, or--to end parameter parsing. #starts a comment only at the beginning of a token;&,;,|,(,{and@are special in argument mode — quote such names.- Native programs receive arguments as text. Since 7.3,
$PSNativeCommandArgumentPassing(Windowson Windows,Standardelsewhere) passes empty strings and embedded quotes correctly.--%(stop-parsing) sends the rest of the line to the program unchanged — useful forcmd-style arguments, but it disables variable expansion.
\ escapes like in Bash” — the backtick does. ② “Double quotes are safer” — single quotes are; double quotes expand $5 and $name. ③ “"$obj.Name" prints the property” — it prints the object then .Name. ④ “Get-ChildItem handles brackets” — only with -LiteralPath or escaping. ⑤ “A backtick at line end is fine” — one invisible trailing space breaks it.Diagram: one line, two modes
Interactive parser: how is this line read?
Pick a line and step through how the parser classifies each token and what the command finally receives. All results were reproduced on 7.6.10.
Command reference
| Syntax | Meaning | Notes |
|---|---|---|
'…' / "…" | Literal / expanding string | 'it''s' doubles a single quote |
"$( expr )" | Subexpression inside a string | Members, indexes, method calls |
@' … '@ / @" … "@ | Here-strings | Opening marker ends its line; closing marker starts a line |
`n `t `$ `" `` | Escapes in double quotes | Backtick, not backslash |
-LiteralPath | No wildcard interpretation | Alias -LP, -PSPath |
[WildcardPattern]::Escape($s) | Escape * ? [ ] for -Path | Useful with -like too |
-- | Everything after is an argument | For names starting with - |
--% | Stop parsing: pass the rest literally to a native program | No variable expansion after it |
$PSNativeCommandArgumentPassing | How arguments are quoted for native programs | Windows (default on Windows), Standard, Legacy |
Write-Output 2+3 Write-Output (2+3) 2+3 $n = @(3, 5, 8) "Items: $n.Count" "Items: $($n.Count)" Write-Output "Tab:`tEnd" 'Tab:`tEnd'
2+3 5 5 Items: 3 5 8.Count Items: 3 Tab: End Tab:`tEnd
Set-Location ~/pslab Get-ChildItem './data/files/[draft] notes.md' | Measure-Object | Select-Object -ExpandProperty Count Get-ChildItem -LiteralPath './data/files/[draft] notes.md' | Select-Object -ExpandProperty Name Get-Content './data/files/`[draft`] notes.md' Get-Content './data/files/price $5.txt' Get-Content "./data/files/price $5.txt"
0 [draft] notes.md file #3 file #4 Get-Content: Cannot find path '…/data/files/price .txt' because it does not exist.
How to verify: the plain -Path call found 0 items and raised no error — a wildcard that matches nothing is silent. In double quotes, $5 is a variable (undefined, so empty). Common mistake: building paths with double quotes from user input. Production use: single quotes for literals, -LiteralPath whenever the name comes from data (CSV, API, user), and Join-Path to combine.
Get-Content -WhatIf.txt # read as a parameter
Get-Content -LiteralPath ./data/files/-WhatIf.txt
Get-Content -- ./data/files/-WhatIf.txt
[WildcardPattern]::Escape('[draft] notes.md')
$PSNativeCommandArgumentPassing
Get-Content: A parameter cannot be found that matches parameter name 'WhatIf'. file #7 file #7 `[draft`] notes.md Windows
Goal: Read every odd-named file in files/ safely and print a table of name and content. Environment: pwsh 7.6 in ~/pslab. Cost: none; the lab only reads.
-Path) — count the failures:
$names = Get-ChildItem ./data/files -File -Recurse -Force -Name
$ok = 0; $bad = 0
foreach ($n in $names) {
$c = Get-Content -Path "./data/files/$n" -ErrorAction SilentlyContinue
if ($c) { $ok++ } else { $bad++; "FAILED: $n" }
}
"ok=$ok bad=$bad"
FAILED: [draft] notes.md ok=11 bad=1
The bracket name is a wildcard pattern that matches nothing, and SilentlyContinue hid the reason. price $5.txt survives because $n is expanded once and its value is not re-parsed. tick`mark.txt also survives: a backtick before an ordinary letter is kept literally by the wildcard matcher in 7.6 (a backtick before [, ], * or ? would escape it).
PSPath, or use -LiteralPath:
Get-ChildItem ./data/files -File -Recurse -Force |
Select-Object Name, @{ n = 'Content'; e = { Get-Content -LiteralPath $_.FullName } } |
Sort-Object Content
Name Content ---- ------- report 2026.txt file #1 café-ünïcode.txt file #10 .hidden.txt file #11 nested file.log file #12 two spaces.txt file #2 [draft] notes.md file #3 price $5.txt file #4 it's.txt file #5 tick`mark.txt file #6 -WhatIf.txt file #7 #hash.txt file #8 a&b;c.txt file #9
Contents sort as text, so file #10–#12 follow file #1. Sort with @{ e = { [int]($_.Content -replace '\D') } } for numeric order (regex: Lesson 2).
Set-Location ./data/files Get-Content -LiteralPath 'price $5.txt', "it's.txt", 'tick`mark.txt', './-WhatIf.txt', '#hash.txt', 'a&b;c.txt' Set-Location ~/pslab
In single quotes $, `, #, & and ; are all literal; "it's.txt" uses double quotes because it contains a single quote (or write 'it''s.txt').
$s = Import-Csv ./data/servers.csv @" Servers : $($s.Count) Prod : $(@($s | Where-Object Env -eq 'prod').Count) Edge : $(($s | Where-Object Role -like '*,*').Name) "@
Servers : 12 Prod : 6 Edge : edge-01
Case 1: a function silently ignored “-join”
Problem: While writing this lesson's integrated lab, a check reported dev prod staging instead of dev,prod,staging. The call was New-Check 'config environments' 'dev,prod,staging' (… | Sort-Object) -join ','. Root cause: in argument mode, -join after the parenthesized argument is not an operator; it is read as another parameter-like argument. A simple (non-advanced) function puts unknown arguments in $args without an error, so the array was later stringified with spaces. Fix: wrap the whole expression: ((… | Sort-Object) -join ','). Advanced functions with [CmdletBinding()] (Lesson 3) reject unknown parameters and would have failed loudly.
Case 2: a cleanup removed the wrong files
Problem: Remove-Item "$root\$name", with $name from a ticket, received backup[1].zip. -Path treated [1] as a character class and deleted backup1.zip instead. Fix: Remove-Item -LiteralPath (Join-Path $root $name); test destructive commands with -WhatIf first.
Case 3: a password with a dollar sign
Problem: A service account password containing $Pr0d stopped working when moved from single to double quotes in a script. Root cause: double quotes expanded $Pr0d to an empty string. Fix: never put secrets in scripts at all; use SecretManagement or a vault (Lesson 7). If you must write a literal, use single quotes.
Common errors and fixes
Cannot find path '…' because it does not exist (but the file exists)
Cause: wildcard characters in a -Path argument, or $ expanded inside double quotes.
Get-ChildItem -LiteralPath $dir -Force | Where-Object Name -eq $name
Fix: -LiteralPath, single quotes, Join-Path.
A parameter cannot be found that matches parameter name '…'
Cause: an argument starts with - (a file name, a negative-looking value), or a typo in a parameter name.
Fix: ./-name, -LiteralPath, or --.
Missing closing '}' / The string is missing the terminator
Cause: unbalanced quotes; a here-string closing marker indented or followed by text; curly “smart quotes” pasted from a document.
Fix: the closing '@ / "@ must be at the start of its line; retype quotes in the editor.
A native program receives the wrong arguments (quotes lost or doubled)
Cause: 5.1's legacy argument passing, or the program does its own parsing (cmd.exe, msiexec).
$PSNativeCommandArgumentPassing
Trace-Command -Name NativeCommandParameterBinder -PSHost -Expression { git log --format="%h %s" -1 }
Fix: in 7.x keep the default; for cmd-style tools use an argument array or --%.
1. Print: Path is C:\Temp and cost is $5 (with the literal $5).
$p = 'C:\Temp' "Path is $p and cost is `$5" 'Path is ' + $p + ' and cost is $5'
2. Count .md files under ./data/files whose name contains '[' using a wildcard pattern safely.
Get-ChildItem ./data/files -File | Where-Object Name -like "*$([WildcardPattern]::Escape('['))*"A script calls az vm list --query "[?location=='eastus'].name" -o tsv and works in Bash but returns nothing in PowerShell 5.1. Why, and what do you do in 7.x?
5.1's legacy native-argument passing re-quotes arguments containing quotes, so az receives a mangled JMESPath query. PowerShell 7.3+ ($PSNativeCommandArgumentPassing) passes it correctly. In 5.1 or edge cases, put the query in a variable with single quotes, or use --%, or better, use the Az PowerShell module, which returns objects (Lesson 7).
Verified teaching videos
No verified video was found that specifically covers parsing modes and -LiteralPath; the documentation below and this module's animation are the reference.
Official documentation
Video storyboard (about 90 seconds)
Visual: “2+3” typed alone → 5; after Write-Output → the text 2+3; parentheses light up → 5.
Narration: commands put you in argument mode; parentheses take you back to expressions.
Visual: “Count: $s.Count” prints the whole array then “.Count”; $( ) fixes it.
Narration: inside double quotes, only the simple variable name expands. Use $( ) for anything more.
Visual: a file “[draft] notes.md”; -Path finds nothing, -LiteralPath finds it.
Narration: brackets are wildcards. Data-driven names always go to -LiteralPath.
Module 8 · Your first script: .ps1, param(), execution policy and exit codes
- Write a script with comment-based help,
#Requires,[CmdletBinding()]and aparam()block with defaults, and use$PSScriptRootfor paths relative to the script. - Explain the execution policy (Restricted, RemoteSigned, AllSigned, Bypass; scopes) and why it is not a security boundary.
- Compare
& ./x.ps1,. ./x.ps1,pwsh -Fileandpwsh -Command: variables, location, exit code. - Return objects on the success stream, write diagnostics to the right stream, and end with meaningful exit codes (0 ok, 1 failure, 2 usage).
What: anatomy of a script
<#
.SYNOPSIS
One line: what the script does.
.EXAMPLE
./Get-DataInfo.ps1 | Sort-Object Lines -Descending
#>
#Requires -Version 7.4
[CmdletBinding()] # common parameters: -Verbose, -ErrorAction …
param(
[Parameter(Position = 0)]
[string]$Path = (Join-Path $PSScriptRoot '..' 'data'),
[switch]$IncludeHidden
)
# … body: output objects …
exit 0
Comment-based help must be the first thing in the file. While writing this lesson, placing #Requires above the help block made Get-Help ignore the help entirely (verified on 7.6.10) — keep the order shown.
Why: execution policy exists, but is not security
| Policy | Effect | Default for |
|---|---|---|
Restricted | No scripts at all (commands only) | Windows PowerShell 5.1 on Windows client |
RemoteSigned | Local scripts run; scripts marked as downloaded (Zone.Identifier) need a signature | pwsh on Windows, Windows Server |
AllSigned | Every script must be signed by a trusted publisher | High-security environments |
Bypass / Unrestricted | Nothing blocked / warns for downloaded scripts | Automation, CI agents |
Scopes from highest precedence: MachinePolicy, UserPolicy (Group Policy), Process, CurrentUser, LocalMachine. On Linux and macOS the policy is Unrestricted and cannot be changed. The policy prevents accidental execution: anyone can bypass it (pwsh -ExecutionPolicy Bypass, pasting the content). Real controls are AppLocker / WDAC, code signing with constrained language mode, and least privilege.
How: four ways to run a script
| Invocation | New process? | Script's variables after it ends | Set-Location inside the script | Exit code you see |
|---|---|---|---|---|
& ./x.ps1 or ./x.ps1 | No | Gone (script scope) | Changes your location (location belongs to the runspace) | $LASTEXITCODE = value of exit N |
. ./x.ps1 (dot-source) | No | Kept in your scope | Changes your location | Same |
pwsh -File ./x.ps1 | Yes | Gone | Isolated | The exit N value; 1 if the script throws |
pwsh -Command "./x.ps1" | Yes | Gone | Isolated | 0 or 1 — from $? of the last command, not exit N |
The last row surprises most people: with -Command, a script that does exit 3 makes the process exit with 1 (verified on 7.6.10). Use -File, or end the command string with ; exit $LASTEXITCODE.
When: output vs messages
Everything a script emits on the success stream (bare values, Write-Output) is its result and can be captured or piped. Write-Host writes to the host via the information stream and is not captured by $x = ./script.ps1. Use Write-Verbose for diagnostics, Write-Warning for warnings, Write-Error for errors (Lesson 5 covers streams fully). Exit codes are for the process boundary (schedulers, CI); inside PowerShell, objects and errors are the richer contract.
Set-Location inside it moves you (unlike Bash). ② “exit 3 always gives exit code 3” — not with pwsh -Command. ③ “Write-Host is how scripts return data” — it is for display only. ④ “Bypass is insecure, so RemoteSigned makes us secure” — neither is a security boundary. ⑤ “$PWD is the script's folder” — it is wherever the caller is; use $PSScriptRoot.Diagram: the run path of ./Get-DataInfo.ps1
Script run path: which invocation, which result?
Choose how Get-DataInfo.ps1 (or a test script that does exit 3) is run, then step through scope, location and exit code. Below the animation is the interactive troubleshooting tree.
Interactive troubleshooting tree: my script will not run
Command reference
| Command | Purpose | Notes |
|---|---|---|
Get-ExecutionPolicy -List | Policy per scope | The first defined scope from the top wins |
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned | Allow your local scripts | No admin needed |
Unblock-File ./x.ps1 | Remove the “downloaded” mark | Only after you read the script |
& $path @args | Call operator | Required when the path is in a variable or quoted |
. ./lib.ps1 | Dot-source into the current scope | For libraries and profiles |
$PSScriptRoot, $PSCommandPath | Script folder / full path | Empty at the prompt |
exit N, $LASTEXITCODE | Set / read an exit code | $? is only success/failure of the last command |
Get-Help ./x.ps1 -Full | Read your script's help | Help block first in the file |
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Bypass
LocalMachine RemoteSigned
# A test script that sets an exit code Set-Content ./scripts/exit.ps1 -Value @' [CmdletBinding()] param([Parameter(Mandatory)][int]$Code) Write-Output "exiting with $Code" exit $Code '@ pwsh -NoProfile -File ./scripts/exit.ps1 -Code 3; "LASTEXITCODE=$LASTEXITCODE" pwsh -NoProfile -Command './scripts/exit.ps1 -Code 3'; "LASTEXITCODE=$LASTEXITCODE" pwsh -NoProfile -Command './scripts/exit.ps1 -Code 3; exit $LASTEXITCODE'; "LASTEXITCODE=$LASTEXITCODE" & ./scripts/exit.ps1 -Code 5; "in-process: LASTEXITCODE=$LASTEXITCODE ?=$?"
exiting with 3 LASTEXITCODE=3 exiting with 3 LASTEXITCODE=1 exiting with 3 LASTEXITCODE=3 exiting with 5 in-process: LASTEXITCODE=5 ?=False
How to verify: line 4 shows the -Command trap. Common mistake: a CI step pwsh -Command ./deploy.ps1 that turns every specific failure code into 1. Production use: schedulers and CI call pwsh -NoProfile -NonInteractive -File script.ps1 ….
# Location is shared with the caller Set-Content ./scripts/where.ps1 -Value 'Set-Location (Join-Path $PSScriptRoot ".." "data"); "script cwd: $(Split-Path $PWD -Leaf)"' Set-Location ~/pslab & ./scripts/where.ps1; "after &: $(Split-Path $PWD -Leaf)"
script cwd: data after &: data
In Bash, ./script.sh runs in a child process and cannot change your directory. In PowerShell the current location belongs to the runspace, so a script run with & moves you too. Use Push-Location/Pop-Location in a try/finally, or avoid changing location in scripts.
Goal: Write ~/pslab/scripts/Get-DataInfo.ps1, which outputs one object per data file, and call it every way. Environment: pwsh 7.6, VS Code. Cost: none.
code ~/pslab/scripts/Get-DataInfo.ps1, paste, save):
<#
.SYNOPSIS
Summarizes the files in a data folder as objects.
.EXAMPLE
./Get-DataInfo.ps1 | Sort-Object Lines -Descending
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$Path = (Join-Path $PSScriptRoot '..' 'data'),
[switch]$IncludeHidden
)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
Write-Error "Get-DataInfo: folder not found: $Path"
exit 2
}
Get-ChildItem -LiteralPath $Path -File -Recurse -Force:$IncludeHidden | ForEach-Object {
[pscustomobject]@{
Name = $_.Name
Folder = Split-Path $_.DirectoryName -Leaf
SizeBytes = $_.Length
Lines = @(Get-Content -LiteralPath $_.FullName).Count
}
}
exit 0Set-Location ~/pslab ./scripts/Get-DataInfo.ps1 | Sort-Object Lines -Descending | Select-Object -First 5 (./scripts/Get-DataInfo.ps1).Count (Get-Help ./scripts/Get-DataInfo.ps1).Synopsis
Name Folder SizeBytes Lines ---- ------ --------- ----- access.log data 80646 611 inventory.json data 1599 14 opskit.config.psd1 data 777 14 servers.csv data 600 13 -WhatIf.txt files 8 1 16 Summarizes the files in a data folder as objects.
./scripts/Get-DataInfo.ps1 -Path ./nope; "LASTEXITCODE=$LASTEXITCODE" pwsh -NoProfile -File ./scripts/Get-DataInfo.ps1 ./nope 2>$null; "via -File: $LASTEXITCODE" pwsh -NoProfile -Command './scripts/Get-DataInfo.ps1 ./nope' 2>$null; "via -Command: $LASTEXITCODE"
Write-Error: Get-DataInfo: folder not found: ./nope LASTEXITCODE=2 via -File: 2 via -Command: 1
Set-Content ./scripts/vars.ps1 -Value '$FromScript = "I was set by vars.ps1"' & ./scripts/vars.ps1; "after &: [$FromScript]" . ./scripts/vars.ps1; "after . : [$FromScript]"
after &: [] after . : [I was set by vars.ps1]
$r = Write-Host 'visible'; "captured=[$r]" $o = Write-Output 'data'; "captured=[$o]"
visible captured=[] captured=[data]
Case 1: CI always reported exit code 1
Problem: A deployment script returned 3 for “drift detected — needs approval” so that the pipeline could branch on it, but the CI step always saw 1. Root cause: the step used pwsh -Command ./deploy.ps1. Fix: pwsh -NoProfile -NonInteractive -File ./deploy.ps1. GitHub Actions' shell: pwsh appends if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE } to your script for this reason.
Case 2: a script that worked only from its own folder
Problem: Import-Csv .\servers.csv inside a script failed when Task Scheduler started it (current folder: C:\Windows\System32). Fix: Join-Path $PSScriptRoot 'servers.csv'.
Case 3: “Bypass everywhere” in a hardening audit
Problem: Auditors flagged -ExecutionPolicy Bypass in every scheduled task. Discussion: Bypass is normal for automation because the policy is not a boundary; the real questions are who can write the script files (ACLs), whether scripts are signed when policy requires it, and whether WDAC/AppLocker enforce constrained language mode for untrusted code.
Common errors and fixes
File C:\…\x.ps1 cannot be loaded because running scripts is disabled on this system
Get-ExecutionPolicy -List Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
If MachinePolicy/UserPolicy is set, Group Policy controls it — ask your administrator.
File … is not digitally signed. You cannot run this script on the current system
Cause: RemoteSigned + the file carries a “downloaded from the internet” mark.
Get-Item ./x.ps1 -Stream Zone.Identifier -ErrorAction Ignore Unblock-File ./x.ps1 # after reading it
The script 'x.ps1' cannot be run because it contained a "#requires" statement for PowerShell 7.4 …
Cause: you ran it in Windows PowerShell 5.1 or an old pwsh.
Fix: run it with pwsh; check $PSVersionTable.
Get-Help shows only the syntax of my script
Cause: the comment-based help block is not the first thing in the file (for example #Requires above it) or a keyword is misspelled.
Fix: move the <# .SYNOPSIS … #> block to line 1.
1. Run Get-DataInfo.ps1 from another folder without changing your location, and save its objects as JSON.
Set-Location ~ & ~/pslab/scripts/Get-DataInfo.ps1 | ConvertTo-Json | Set-Content ~/pslab/tmp/datainfo.json
It works from any folder because the default path uses $PSScriptRoot.
2. Write the command line a Windows scheduled task should use for this script.
pwsh.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\Users\labadmin\pslab\scripts\Get-DataInfo.ps1" -Path "D:\data"
Your script calls Set-Location $deployDir at the start. Colleagues complain that after running it their prompt is “somewhere else”, and a second script they run next fails. What do you change?
Location belongs to the runspace, so the script changes the caller's location. Wrap it: Push-Location $deployDir; try { … } finally { Pop-Location }, or better, avoid relying on the current location at all and build full paths with Join-Path. The second script failing shows why scripts should never depend on $PWD.
Verified teaching videos
Official documentation
- about_Scripts · about_Execution_Policies · about_Pwsh (-File vs -Command exit codes) · about_Automatic_Variables
Video storyboard (about 90 seconds)
Visual: a .ps1 file assembles: help block, #Requires, param(), body, exit.
Narration: help first, then requirements, then parameters.
Visual: four doors — &, dot, -File, -Command — with what comes out of each: variables, location, exit code.
Narration: dot-sourcing keeps variables; -Command flattens exit codes to 0 or 1.
Visual: a scheduled task line with -NoProfile -NonInteractive -File highlighted.
Narration: automation uses -NoProfile, -NonInteractive and -File.
Command cheat sheet
1. Edition, host and startup
$PSVersionTable.PSVersion; $PSVersionTable.PSEdition # Core = 7.x $Host.Name # ConsoleHost, Visual Studio Code Host $PROFILE | Select-Object * # four profile paths pwsh -NoProfile -NonInteractive -File ./x.ps1 # automation $IsWindows; $IsLinux; $IsMacOS
2. Commands and precedence
Get-Command name -All # alias → function → cmdlet → external Get-Command -Verb Get -Noun *Item* Get-Alias -Definition Get-ChildItem Microsoft.PowerShell.Management\Get-ChildItem # bypass shadows curl.exe / where.exe / sort.exe # the native tool on Windows
3. Discovery
Update-Help -Scope CurrentUser -ErrorAction SilentlyContinue Get-Help Get-ChildItem -Examples Get-Help Get-ChildItem -Parameter Path Get-Command Get-ChildItem -Syntax Get-Help about_* # concepts Get-Verb
4. Objects and formatting
X | Get-Member
$x.GetType().FullName
X | Format-List * # explore
[pscustomobject]@{ Name = 'a'; Size = 1 }
X | Sort-Object Length | Format-Table Name, Length # format LAST5. Pipeline binding
# ByValue → ByPropertyName (incl. aliases such as PSPath)
(Get-Command Get-Content).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipelineByPropertyName -contains $true }
Trace-Command -Name ParameterBinding -PSHost -Expression { A | B }
A | Select-Object @{ n = 'Name'; e = { $_.X } } | B
A | ForEach-Object { B -Param $_.X }
-PipelineVariable v6. Filtering and shaping
Where-Object Env -eq 'prod'
Where-Object { $_.Monitored -eq 'true' -and $_.Role -like '*web*' }
Select-Object -First 5 Name, @{ n = 'KB'; e = { $_.Length / 1KB } }
Select-Object -ExpandProperty Name
Sort-Object Env, Name; Group-Object Env -NoElement
Measure-Object Length -Sum -Average -Maximum
Get-ChildItem -Recurse -Filter *.log # filter left7. Quoting and wildcards
'literal $x' "expands $x and $($obj.Prop)"
@'
literal here-string
'@
"tab`t newline`n dollar `$"
Get-Content -LiteralPath '[draft] notes.md'
Get-Content -- ./-WhatIf.txt
[WildcardPattern]::Escape('[a]') # `[a`]8. Scripts
<# .SYNOPSIS … #> # help block FIRST #Requires -Version 7.4 [CmdletBinding()] param([string]$Path = (Join-Path $PSScriptRoot 'data')) & ./x.ps1 # call (shares location!) . ./lib.ps1 # dot-source (keeps variables) exit 2; $LASTEXITCODE Get-ExecutionPolicy -List Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
Integrated lab + final quiz
~/pslab/Test-LabData.ps1: validate the dataset with objects instead of text parsing, read odd names safely, save results as JSON and return meaningful exit codesScenario
Lessons 2–9 depend on ~/pslab/data. Write a “dataset health check” to run before each lesson: it outputs one result object per check, writes all results to ~/pslab/tmp/Test-LabData.json, exits 0 when everything passes, 1 when any check fails (with a warning naming the failed checks), and 2 when the data folder does not exist.
~/pslab/Test-LabData.ps1:
<#
.SYNOPSIS
Checks that the dataset generated by New-LabData.ps1 is complete.
.DESCRIPTION
Exit codes: 0 all checks passed; 1 at least one check failed; 2 usage error.
.EXAMPLE
./Test-LabData.ps1
./Test-LabData.ps1 -Path ~/pslab/data -LogPath ~/pslab/tmp/check.json
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
[string]$Path = (Join-Path $HOME 'pslab' 'data'),
[string]$LogPath = (Join-Path $HOME 'pslab' 'tmp' 'Test-LabData.json')
)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
Write-Error "Test-LabData: data folder not found: $Path"
exit 2
}
function New-Check([string]$Name, $Expected, $Actual) {
[pscustomobject]@{
Check = $Name
Expected = "$Expected"
Actual = "$Actual"
Passed = "$Expected" -eq "$Actual"
}
}
$log = Join-Path $Path 'access.log'
$servers = Import-Csv -LiteralPath (Join-Path $Path 'servers.csv')
$files = Join-Path $Path 'files'
$results = @(
New-Check 'access.log lines' 611 @(Get-Content -LiteralPath $log).Count
New-Check '5xx responses' 20 (Select-String -LiteralPath $log -Pattern '" 5\d\d ').Count
New-Check 'busiest client' '198.51.100.23' (
Get-Content -LiteralPath $log | ForEach-Object { ($_ -split ' ')[0] } |
Group-Object -NoElement | Sort-Object Count -Descending | Select-Object -First 1).Name
New-Check 'servers' 12 $servers.Count
New-Check 'prod servers' 6 @($servers | Where-Object Env -eq 'prod').Count
New-Check 'monitored servers' 8 @($servers | Where-Object { $_.Monitored -eq 'true' }).Count
New-Check 'multi-role server' 'edge-01' ($servers | Where-Object Role -like '*,*').Name
New-Check 'odd file names' 12 @(Get-ChildItem -LiteralPath $files -File -Recurse -Force).Count
New-Check '[draft] notes.md' 'file #3' (Get-Content -LiteralPath (Join-Path $files '[draft] notes.md'))
New-Check 'config environments' 'dev,prod,staging' ((
(Import-PowerShellDataFile -LiteralPath (Join-Path $Path 'opskit.config.psd1')).Environments.Keys | Sort-Object) -join ',')
)
$results | ConvertTo-Json | Set-Content -LiteralPath $LogPath
$results # objects for the caller
$failed = @($results | Where-Object { -not $_.Passed })
if ($failed.Count -gt 0) {
Write-Warning "$($failed.Count) check(s) failed: $($failed.Check -join ', ')"
exit 1
}
exit 0
Note the double parentheses around the last check's value: without them, -join would be parsed in argument mode as a separate argument (Module 7, Case 1 — this exact bug happened while writing the lab).
Set-Location ~/pslab ./Test-LabData.ps1 | Format-Table; "exit=$LASTEXITCODE"
Check Expected Actual Passed ----- -------- ------ ------ access.log lines 611 611 True 5xx responses 20 20 True busiest client 198.51.100.23 198.51.100.23 True servers 12 12 True prod servers 6 6 True monitored servers 8 8 True multi-role server edge-01 edge-01 True odd file names 12 12 True [draft] notes.md file #3 file #3 True config environments dev,prod,staging dev,prod,staging True exit=0
Rename-Item -LiteralPath './data/files/[draft] notes.md' -NewName 'draft notes.md'
./Test-LabData.ps1 2>$null | Where-Object { -not $_.Passed }; "exit=$LASTEXITCODE"
./New-LabData.ps1 | Out-Null # repair
WARNING: 1 check(s) failed: [draft] notes.md Check Expected Actual Passed ----- -------- ------ ------ [draft] notes.md file #3 False exit=1
pwsh -NoProfile -NonInteractive -File ./Test-LabData.ps1 | Out-Null; "exit=$LASTEXITCODE" ./Test-LabData.ps1 -Path ./nope; "exit=$LASTEXITCODE" (Get-Content ./tmp/Test-LabData.json -Raw | ConvertFrom-Json)[0]
exit=0 Write-Error: Test-LabData: data folder not found: ./nope exit=2 Check : access.log lines Expected : 611 Actual : 611 Passed : True
Open-ended self-check
1. Walk through what happens for Get-ChildItem ./data -File | Sort-Object Length | Format-Table Name, Length, from the host to the screen.
The host passes the line to the engine; the parser builds an AST with three commands; command discovery resolves each name (no aliases or functions shadow them → cmdlets); named and positional arguments bind (./data → -Path, position 0); BeginProcessing runs for all three; Get-ChildItem streams FileInfo objects; Sort-Object collects them (blocking) and emits sorted objects in EndProcessing; Format-Table turns them into format records; the implicit Out-Default sends them to the host, which renders text.
2. Why does Get-Item x | Get-Content handle a name like [a].txt correctly while Get-Content [a].txt does not?
Piped FileInfo binds by property name through PSPath, an alias of -LiteralPath. Typed text binds to -Path, where brackets are wildcards.
3. Name three things a script should never rely on, and what to use instead.
Profile contents (→ parameters, explicit imports, -NoProfile); the current location (→ $PSScriptRoot, Join-Path); aliases (→ full cmdlet names). Also: interactive prompts (→ -NonInteractive and mandatory parameters supplied by the caller).
4. Give two ways to make pwsh -Command report a script's real exit code.
Use pwsh -File script.ps1, or append ; exit $LASTEXITCODE to the command string.
Sources and version notes
| Topic | Verified result | Sources (accessed 2026-11-24) |
|---|---|---|
| Current releases | PowerShell 7.6 is the current LTS (GA 2026-03-18, end of support 2028-11-14), built on .NET 10. The lifecycle page listed 7.6.6 as the current LTS patch and 7.5.11 as the latest 7.5; PowerShell 7.4 LTS and 7.5 reach end of support on 2026-11-10; 7.7 is in preview. The lab machine ran 7.6.10 on .NET 10.0.15. | PowerShell support lifecycle; Announcing PowerShell 7.6 |
| What's new in 7.6 | Bundled modules updated (PSResourceGet 1.2.x, PSReadLine 2.4.x, Microsoft.PowerShell.ThreadJob replaces ThreadJob); macOS PKG signed and notarized; WildcardPattern.Escape fixes for lone backticks; Join-Path -ChildPath accepts string[]; many tab-completion improvements | What's New in PowerShell 7.6 |
| Editions | Side-by-side installation, separate profile and module paths, different default encodings | Differences from Windows PowerShell 5.1 |
| Profiles and startup | Four profiles, load order, -NoProfile, -NonInteractive, -File vs -Command exit codes | about_Profiles; about_Pwsh; this lesson's runs |
| Command precedence | Alias → function → cmdlet → external; no current-folder lookup without a path | about_Command_Precedence |
| Pipeline binding | ByValue / ByPropertyName, without then with coercion; Trace-Command ParameterBinding output reproduced on 7.6.10 | about_Pipelines; Trace-Command |
| Parsing and quoting | Expression vs argument mode, quoting rules, backtick escapes, --, --%, wildcards | about_Parsing; about_Quoting_Rules; about_Wildcards |
| Execution policy | Policies, scopes, defaults; not a security boundary | about_Execution_Policies |
| Container image | mcr.microsoft.com/powershell has lts and latest tags | MCR tag list |
| Sample dataset | New-LabData.ps1 run twice on 7.6.10 produced identical files; SHA-256 prefixes: access.log A0A0D5B9D3B4C974, inventory.json 6E3808C1DB0D3276, opskit.config.psd1 381E684642929B30, servers.csv 6323C180C2EFF12E | Actual runs for this lesson |
Video verification notes
This lesson lists only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24:
- PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training (Modules 1–5)
- Microsoft PowerShell for Beginners - Video 1 Learn PowerShell — Shane Young (Modules 1, 8)
- Learn PowerShell in Less Than 2 Hours — K12 Engineer (Modules 2, 4, 6, 8)
- PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson (Modules 3, 5, 7)
oEmbed only verifies titles and channels; the videos were not watched segment by segment, and the “meta” descriptions come from titles and public information. Most of these videos use Windows PowerShell 5.1 or early PowerShell 7 releases; where behavior differs, this lesson is authoritative. No verified video was found that specifically covers pipeline parameter binding rules, parsing modes or -File vs -Command exit codes; use this lesson's animations and the documentation.
Voice narration notes
The “Voice” tab uses the browser's built-in Web Speech API to read the narration script (en-US); it needs no network access or external scripts. The courseware cannot embed MP3 files or generate video; the narration and storyboards can be passed to a TTS or video tool.
Known limitations
- Run environment: outputs labeled “Actual output (7.6.10)” were produced on Windows 11 with PowerShell 7.6.10; paths were replaced with
C:\Users\labadmin\pslab\…or shortened. The lab machine has extra modules installed (Az, Pester 3.4 from Windows), which affects counts such as the number of available commands, so those counts are not quoted. Not run on Linux or macOS: cross-platform differences (aliases, hidden files, profile paths) are taken from the documentation and labeled accordingly. - Outputs labeled “Expected output / example” were not run as shown; process IDs, dates and patch numbers in them are illustrative.
- Help content was not installed on the lab machine (to show the “partial help” state); the
Update-Helpstep and-Examplesoutput were not captured. - The animations simplify the engine: they omit dynamic parameters, delay-bind script blocks, the exact order of positional binding across parameter sets, and module auto-loading details.
- Execution policy defaults depend on the OS edition and Group Policy; use
Get-ExecutionPolicy -Liston your machine as the reference.