PowerShell Lesson 1: How PowerShell Works — Objects, Commands and the Pipeline

Starting from “what happens after you press Enter in pwsh”: editions and hosts, the kinds of commands and how one is chosen, discovering commands, objects and the formatting system, pipeline parameter binding, filtering and shaping data, parsing modes and quoting, and finally a first script with proper exit codes
PowerShell 7.6 LTS (7.6.10)Compared with Windows PowerShell 5.1Local only · FreeVerified · 2026-11-24
Position in the Learning Path Linux → Bash → Git → PowerShell → Docker → Kubernetes → Terraform → Ansible → … The previous courses taught a text shell: in Bash every command reads and writes lines of text, and you glue them together with 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).
Overall Learning Objectives
  • 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 that pwsh -File still loads profiles unless you pass -NoProfile.
  • Use Get-Command -All to 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 with Get-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: ByValue first, then ByPropertyName — this lesson's core animation — and confirm it with Trace-Command.
  • Filter and shape data with Where-Object, Select-Object (calculated properties), Sort-Object, Group-Object and Measure-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 -LiteralPath for names like [draft] notes.md.
  • Write a first .ps1 script with param(), $PSScriptRoot and explicit exit codes, run it with &, dot-sourcing and pwsh -File, and know why pwsh -Command can turn exit code 3 into 1.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassEnvironment setupPowerShell 7.6 on Windows / macOS / Linux / container, VS Code + PowerShell extension, ~/pslab, New-LabData.ps1 to generate the sample datasetEnvironment self-check checklistGenerate ~/pslab/data/ and verify SHA-256 hashes
100–06What PowerShell isEngine, host, runspace; pwsh vs powershell.exe; .NET 10; LTS lifecycle; profiles; -NoProfile, -File, -CommandStartup simulator: which profiles and settings loadIdentify edition, host and profile paths
206–13CommandsCmdlet, function, alias, filter, ExternalScript, Application; Verb-Noun; precedence; module-qualified namesCommand resolverMake one name an alias, a function and a cmdlet at once
313–21DiscoveryGet-Command, Get-Help, -Examples, about_* topics, syntax diagrams, parameter sets, Get-VerbSyntax diagram decoderAnswer questions about a cmdlet using only help
421–28Objects and formatting.NET types, properties, methods, Get-Member, PSCustomObject, default views, Format-Table / Format-List, “format right”Object vs text: what travels down the pipeInspect Import-Csv and Get-Item objects
528–35Pipeline and bindingStreaming one object at a time; begin / process / end; ByValue, ByPropertyName, aliases such as PSPath; Trace-Commandcore animation: pipeline parameter bindingProve which parameter receives a FileInfo object
635–42Filtering and shapingWhere-Object, Select-Object, calculated properties, Sort-Object, Group-Object, Measure-Object, .Where(), filter leftPipeline stage-by-stage data viewServer inventory report from servers.csv
742–50Parsing and quotingExpression vs argument mode; quotes; $( ); here-strings; backtick; --; --%; native arguments; wildcards and -LiteralPathInteractive parser: how is this line read?Handle the odd file names in files/
850–60First script.ps1, param(), #Requires, execution policy, & vs ., $PSScriptRoot, exit, $LASTEXITCODE, -File vs -CommandScript run path animation + troubleshooting treeWrite ~/pslab/scripts/Get-DataInfo.ps1
—After ClassCheat sheet · Integrated labWrite Test-LabData.ps1: validate the dataset with objects, handle odd names safely and return meaningful exit codesFinal quiz (12 questions)The script passes every check on ~/pslab/data

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Identify edition, host and startup behavior✓······✓$PSVersionTable, $Host.Name, $PROFILE, pwsh -NoProfileM1
Distinguish command types and precedence·✓✓···✓✓Get-Command -All, Get-Alias, Module\CmdletM2
Discover commands and read help·✓✓✓✓···Get-Help -Examples, Get-Command -Syntax, Get-VerbM3
Work with objects and formatting···✓✓✓·✓Get-Member, Format-Table, [pscustomobject]M4, integrated lab
Predict pipeline parameter binding··✓✓✓✓··Trace-Command ParameterBinding, -PipelineVariableM5
Filter, sort, group and measure···✓✓✓·✓Where-Object, Select-Object, Group-Object, Measure-ObjectM6, integrated lab
Quote and escape correctly·····✓✓✓'…', "…$( )…", @' '@, `, -LiteralPathM7, integrated lab
Write and run scripts with exit codes✓✓····✓✓param(), exit, $LASTEXITCODE, pwsh -FileM8, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Type system details, operators (-eq on arrays, -match, -replace), arrays, hashtables, switch, loops, regex, JSON / CSV conversionNeeds the object and parsing model from this lesson firstLesson 2: Language Essentials
Functions, scope, [CmdletBinding()], parameter validation, writing pipeline-aware functionsBelongs to tool-makingLesson 3
Modules, PSResourceGet, providers in depth, cross-platform paths and encodingsPackaging and environmentLesson 4
Terminating vs non-terminating errors, try/catch, streams, -WhatIfThis lesson only previews exit codesLesson 5
Remoting, jobs, ForEach-Object -Parallel, schedulingMulti-machine administrationLesson 6
REST APIs, Az and AWS.Tools modules, secretsCloud automationLesson 7 (also Azure and AWS courses)
Pester, PSScriptAnalyzer, debugging, signing, CIQuality and releaseLesson 8

How to use these materials

10 pages per module
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.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
Voice narration
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
Version notes Verified 2026-11-24. The course baseline is PowerShell 7.6 LTS (GA 2026-03-18, built on .NET 10, supported until 2028-11-14). The outputs marked “Actual output” were produced on PowerShell 7.6.10 on Windows; Microsoft Learn's lifecycle page listed 7.6.6 as the current LTS patch when it was checked, so use your own $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

Install PowerShell 7.6 side by side with anything you already have, create the working folder ~/pslab, and use New-LabData.ps1 to generate the sample dataset ~/pslab/data/ that Lessons 2–9 use directly
Before class ≈ 10 minRuns locally · FreeDeletes only inside ~/pslab
Prerequisites
  • 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

OptionHow to installNotes
A. Windows 11 / Windows Server (recommended for Lessons 6 and 8)winget install --id Microsoft.PowerShell --source wingetInstalls 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. macOSbrew install --cask powershellThe 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 powershellFollow “Installing PowerShell on Linux” on Microsoft Learn for the exact repository package of your release. The Linux course VM linuxlab works well.
D. Containerdocker run --rm -it -v "$HOME/pslab:/root/pslab" -w /root/pslab mcr.microsoft.com/powershell:ltsLinux-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
FolderPurposeWhich lessons use it
~/pslab/data/Sample dataset (generated by New-LabData.ps1; can be rebuilt at any time)All lessons
~/pslab/scripts/Practice scriptsAll lessons
~/pslab/tmp/Temporary output from labs; safe to deleteAll 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)

FileContentsFacts worth remembering (used in later lessons)
access.log611 lines of nginx combined access log, 2026-11-24 10:00:01–10:29:50 (UTC); methods GET 526 / POST 85Line 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.csvHeader Name,Env,Region,IP,Role,Monitored + 12 rows; dev 3 / staging 3 / prod 6Row 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.jsonThe same 12 servers as JSON, plus "Port": 8080; here Monitored is a real booleanCompared with the CSV in Lesson 2 (ConvertFrom-Json keeps types; CSV makes everything a string)
opskit.config.psd1A 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.logContents 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

Risks and cleanup All deletion in this lesson (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

00:00 – 06:00 · PowerShell is an engine (System.Management.Automation) hosted by a program such as the console, VS Code or a service; the edition, the host and the startup switches decide which profiles, modules and policies are in effect
6 minPowerShell 7.6 · 5.1 comparison★★★★☆
Learning objectives
  • Distinguish the terminal, the host and the engine, and know that pwsh and powershell.exe are different products that install side by side.
  • Read $PSVersionTable, $Host.Name and $PSEdition, and know what Core vs Desktop means.
  • Name the four profile paths in $PROFILE and say which ones load for a given host.
  • Explain -NoProfile, -NonInteractive, -File and -Command, and know that profiles load for scripts too unless you pass -NoProfile — the opposite of Bash, where scripts read no rc files.
Prerequisites: Module 0. Importance:★★★★☆ (most “works on my machine, fails in CI / Task Scheduler” issues start here)

What: terminal, host and engine

LayerWhat it isExamples
TerminalDraws characters and sends keystrokes (ConPTY on Windows, a pty on Unix)Windows Terminal, iTerm2, GNOME Terminal, the VS Code terminal panel
HostA 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 + runspaceSystem.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 runtimeEverything PowerShell returns is a .NET object; cmdlets are .NET classesPowerShell 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”)
Executablepwsh / pwsh.exepowershell.exe
PlatformsWindows, macOS, LinuxWindows only
Runtime.NET (7.6: .NET 10).NET Framework 4.x
StatusActive development; LTS releases follow .NET LTSShips in Windows, security fixes only, no new features
Profile folder (Windows)Documents\PowerShellDocuments\WindowsPowerShell
Module folder (Windows)Documents\PowerShell\Modules + $PSHOME\ModulesDocuments\WindowsPowerShell\Modules
Default file encodingUTF-8 without BOMVaries 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 propertyWindows path (pwsh 7)Loaded by
AllUsersAllHosts$PSHOME\profile.ps1Every host, every user
AllUsersCurrentHost$PSHOME\Microsoft.PowerShell_profile.ps1Every user, this host only
CurrentUserAllHosts~\Documents\PowerShell\profile.ps1You, every host
CurrentUserCurrentHost (the value of $PROFILE itself)~\Documents\PowerShell\Microsoft.PowerShell_profile.ps1You, 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

InvocationProfiles?Interactive prompts?Exit code
pwsh (in a terminal)YesYes—
pwsh -File ./x.ps1 -Arg 1YesYes, unless -NonInteractiveThe script's exit N; 1 if it throws
pwsh -Command "./x.ps1"YesYes, unless -NonInteractive0 or 1, from $? of the last command (Module 8)
pwsh -NoProfile -NonInteractive -File ./x.ps1NoNo — a missing mandatory parameter becomes an errorThe script's exit N
Common misconceptions① “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

TerminalWindows Terminal / iTerm2VS Code panel keys Host ($Host.Name)ConsoleHost · VS Code HostPSReadLine: editing, historyprompt, Read-Host, progressrenders formatted output script text Engine (System.Management.Automation) + runspace parser → AST → command discovery → parameter binder pipeline processor: Begin / Process / End of each command session state: variables · functions · drives · modules · location Out-Default → formatting system (format.ps1xml views) .NET 10 runtime cmdlets are .NET classes · every result is a .NET object (FileInfo, Process, PSCustomObject …) native programs (git, az, ping) are started as processes; their stdout comes back as lines of text The host only decides how things look; the engine decides what happens
Figure 1-1: the terminal draws, the host provides the UI, the engine runs the pipeline, and .NET supplies the objects

Flowchart: what loads when pwsh starts

pwsh starts Read config: powershell.config.json($PSHOME and user) · execution policy · experimental features -NoProfile given? No Run profiles in order AllUsersAllHosts → AllUsersCurrentHost → CurrentUserAllHosts → CurrentUserCurrentHost (subject to execution policy) dot-sourced: they change the session Yes skip all four profiles -File / -Command / interactive prompt-NonInteractive: never prompt, fail instead
Figure 1-2: unlike Bash, the decision is “-NoProfile or not”, not “interactive or not”: scripts started with -File or -Command load profiles by default

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.

Ready.
Real mechanism behind the animation The console host (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

CommandPurposeNotes
$PSVersionTableVersion, edition, OS, platform.PSVersion is a [semver]-like object; compare with -ge [version]'7.4'
$Host.NameWhich host you are inDecides the host-specific profile
$PROFILE | Select-Object *All four profile pathsThe paths are NoteProperties on a string
Test-Path $PROFILEDoes your profile exist?It is not created automatically
$PSHOMEInstall folder of this editionC:\Program Files\PowerShell\7
pwsh -NoProfileStart without profilesUse for all automation and for reproducing bugs
pwsh -NonInteractiveNever promptPrompts (Read-Host, mandatory parameters, -Confirm) become errors
pwsh -File / -CommandRun a script file / a command stringExit-code semantics differ (Module 8)
$IsWindows, $IsLinux, $IsMacOSPlatform checksNot 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.

Look at your real profile paths (read only):
$PROFILE | Select-Object * | Format-List
Test-Path $PROFILE.CurrentUserCurrentHost, $PROFILE.CurrentUserAllHosts
…four paths…
False
False
Compare a child pwsh with and without profiles: count the functions each session has. If any of your profiles defines functions, the first number is larger.
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.

Simulate a profile safely: write a fake profile and dot-source it into a -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).

See -NonInteractive turn a prompt into an error:
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
Cleanup: 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).

Command-line exercises
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).

Scenario analysis
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

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · what PowerShell is, editions, getting started
▶
Microsoft PowerShell for Beginners - Video 1 Learn PowerShell — Shane Young
English · a gentle first look at the console

Official documentation

Video storyboard (about 90 seconds)

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

Shot 1 · 0–15s
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.
Shot 2 · 15–40s
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.
Shot 3 · 40–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% on the Quiz

Module 2 · Commands: cmdlets, functions, aliases, scripts and native programs

06:00 – 13:00 · The same name can be an alias, a function, a cmdlet and an executable at once; PowerShell resolves it in a fixed order, and on Linux some familiar aliases do not exist
7 minGet-Command -All★★★★☆
Learning objectives
  • 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, sort and curl differ between Windows and Linux/macOS.
Prerequisites: Module 1. Importance:★★★★☆

What: six kinds of command

CommandTypeWhat it isExampleWhere it lives
AliasAnother name for a commandgci → Get-ChildItemSession (Alias: drive), modules
Function / FilterPowerShell code with a name; a filter is a function with only a process blockprompt, mkdir (Windows), your ownSession (Function: drive), script modules
CmdletA compiled .NET class deriving from Cmdlet/PSCmdletGet-ChildItemBinary modules (.dll)
ExternalScriptA .ps1 file./New-LabData.ps1Disk; found by path or via PATH
ApplicationAny native executablegit, ping, curl.exeDisk; 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

  1. If the name contains a path separator (./x.ps1, C:\tools\x.exe), run that file. No lookup.
  2. Otherwise: Alias → Function (and filters) → Cmdlet → external (scripts and executables found via PATH, in PATH order).
  3. Module auto-loading: if no loaded command matches, PowerShell searches $env:PSModulePath and imports the module that exports the name.
  4. For security, PowerShell does not run scripts from the current directory by name: New-LabData.ps1 fails; ./New-LabData.ps1 works.

When: bypassing a layer

You wantWrite
The cmdlet even if a function or alias shadows itMicrosoft.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 orderGet-Command name -All
Common misconceptions① “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 name in a pipeline AliasAlias: drive · Set-Aliasplatform-dependent Function / FilterFunction: drivescript modules (.psm1) Cmdletbinary modules (.dll)Verb-Noun, .NET class ExternalScript.ps1 file on diskpath or PATH Applicationgit · ping · curl.exeoutput = text lines Precedence (no path given): Alias → Function → Cmdlet → External script / Application (PATH order) Not loaded yet? Module auto-loading searches $env:PSModulePath for a module that exports the name. Bypass: Module\Cmdlet · name.exe · & 'full\path' · Get-Command name -All lists every match
Figure 2-1: five sources of commands; only Applications return text — everything else returns objects

Command resolver

Pick a name and a platform, then step through how PowerShell decides what actually runs.

Ready.

Command reference

CommandPurposeNotes
Get-Command name -AllEvery command with that name, in precedence orderFirst row is what runs
Get-Command -Verb Get -Noun *Item*Search by verb and nounWildcards allowed
Get-Command -Module Microsoft.PowerShell.UtilityEverything a module exportsTriggers auto-loading
Get-Alias -Definition Get-ChildItemAliases for a commandGet-Alias ls for the reverse
Module\CommandRun a specific module's commandBypasses aliases and functions
(Get-Command x).SourceModule name or file pathFor Applications, the full path
Get-VerbApproved verbsGet-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.

Shadow a cmdlet with a function:
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
Add an alias on top, then inspect the order:
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 the shadows:
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.

Scripts in the current folder need a path:
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.

Command-line exercises
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
Scenario analysis
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

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · cmdlets, Verb-Noun, aliases
▶
Learn PowerShell in Less Than 2 Hours — K12 Engineer
English · hands-on tour of common commands

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
Visual: Get-Command -All output with the first row highlighted.
Narration: when in doubt, ask Get-Command -All.
or score ≥ 70% on the Quiz

Module 3 · Discovery: Get-Command, Get-Help and syntax diagrams

13:00 – 21:00 · You do not memorize PowerShell; you discover it. Three commands — Get-Command, Get-Help and Get-Member — answer almost every “how do I …?” question, once you can read a syntax diagram
8 minUpdate-Help★★★★★
Learning objectives
  • Find commands by verb, noun, module or wildcard with Get-Command.
  • Install help with Update-Help and read -Examples, -Parameter, -Full, -Online and about_* 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.
Prerequisites: Module 2. Importance:★★★★★ (self-sufficiency in every later lesson depends on it)

What: the three discovery commands

QuestionCommandExample
Which command does X?Get-CommandGet-Command -Noun *Service*, Get-Command *json*
How do I use it?Get-HelpGet-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

NotationMeaningExample 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 namedGet-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”).

Common misconceptions① “Get-Help shows nothing useful” — help was never installed; run 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

Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Recurse] [-Depth <uint>] [<CommonParameters>] commandVerb-Nounresolved byprecedence (M2) optional +positional 0outer [ ] = optionalinner [ ] = name optional positional 1single value(no [] after type) switchno value-Recurse:$false named only-Depth 2type: uint common parameters-Verbose -Debug-ErrorAction -WarningAction-OutVariable -PipelineVariable
Figure 3-1: brackets tell you what is optional; types tell you what values are accepted; each syntax block is one parameter set

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.

Ready.

Command reference

CommandPurposeNotes
Update-Help -Scope CurrentUserDownload help contentOnce, then occasionally; -ErrorAction SilentlyContinue hides modules without help
Get-Help X -ExamplesWorked examplesUsually the fastest route
Get-Help X -Parameter PathOne parameter: position, pipeline input, wildcards-Parameter * for all
Get-Help X -OnlineOpen the Microsoft Learn pageWorks without local help
Get-Help about_*List conceptual topicsGet-Help about_Quoting_Rules
Get-Command X -SyntaxSyntax only, no help neededGenerated from metadata
(Get-Command X).ParameterSets.NameParameter set names.Parameters.Keys for all parameters
Show-Command XGUI 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.

Install help (skip if offline; use -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.

Q1: Which command converts objects to JSON?
Get-Command *json*

Expected: ConvertFrom-Json, ConvertTo-Json, Test-Json in Microsoft.PowerShell.Utility.

Q2: How do you get only files, recursively, at most 2 levels deep?
Get-Command Get-ChildItem -Syntax
Get-ChildItem ~/pslab -File -Recurse -Depth 2 | Select-Object -First 3 FullName
Q3: Which parameter of Get-Content accepts pipeline input by property name?
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
Q4: What is the conceptual topic about quoting called, and what does it say about $ 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
Q5: Which verb should a function that “turns on” something use: 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.

Command-line exercises
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
Scenario analysis
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

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · Get-Help, Get-Command, discovering commands
▶
PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson
English · long-form course; use the chapters about help and the pipeline

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: three keys labelled Get-Command, Get-Help, Get-Member unlock three doors.
Narration: find it, learn it, inspect what it returns.
Shot 2 · 20–55s
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.
Shot 3 · 55–90s
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.
or score ≥ 70% on the Quiz

Module 4 · Objects, Get-Member and the formatting system

21:00 – 28:00 · Commands return .NET objects with typed properties and methods; the table you see is drawn by the formatting system only at the very end, which is why Format-* must be the last thing in a pipeline
7 minGet-Member★★★★★
Learning objectives
  • Use Get-Member to 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-Default and format views choose table or list, and why Format-Table in the middle of a pipeline produces garbage.
Prerequisites: Modules 1–3. Importance:★★★★★ (the single biggest mental shift from Bash)

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 typeMeaningExample
PropertyData defined by the .NET typeFileInfo.Length
MethodAn action you call with ()$d.AddDays(-1)
NotePropertyA property PowerShell attached (no type behind it)Every column of Import-Csv
ScriptProperty / AliasPropertyComputed or renamed properties added by PowerShell's type systemProcess.WS → WorkingSet64
CodeProperty, PropertySet, EventLess common extended membersFileInfo.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

  1. Every pipeline you type at the prompt ends with an invisible Out-Default.
  2. 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 with Mode, LastWriteTime, Length, Name.
  3. 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.
  4. Format-Table / Format-List / Format-Wide convert objects into format records (FormatStartData, GroupStartData, FormatEntryData …) that only Out-* 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.

Common misconceptions① “The table shows all properties” — it shows the view; 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

Get-ChildItemFileInfo objectsLength: Int64 Sort-ObjectLength (numeric)still FileInfo Select-ObjectName, LengthPSCustomObject Format-Table→ format recordslast step only Out-Default→ hosttext on screen Anti-pattern: Get-ChildItem | Format-Table Name, Length | Sort-Object Length Sort-Object receives FormatStartData, GroupStartData, FormatEntryData … objects, which have no Length property PowerShell 7.6 raises no error — the table simply comes out unsorted. Export-Csv after Format-Table writes ClassId2e4f51ef… columns Rule: filter left, format right
Figure 4-1: only the last stage should turn objects into something for human eyes

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.

Ready.

Command reference

CommandPurposeNotes
X | Get-MemberType name and members of each distinct type in the input-MemberType Property, -Name *Time*
$x.GetType().FullNameExact .NET typeArrays report System.Object[]
X | Format-List *Every property and valueFor exploration only
X | Format-Table Name, Length -AutoSizeChoose columns for displayLast in the pipeline
[pscustomobject]@{ Name = 'a'; Size = 1 }Create your own objectProperty order is kept
X | Out-String -Width 200Render to text (for logs or emails)Use rarely; prefer objects
$FormatEnumerationLimitHow 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.

A .NET object: find the newest file under 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.

A PSCustomObject from CSV: prove that numbers are strings.
$s = Import-Csv ./data/servers.csv
$s[0].IP.GetType().Name
'10' -gt '9'          # string comparison
[int]'10' -gt [int]'9'
String
False
True
Your own object: one summary object per file, with typed properties.
$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.

See the views: compare default output with 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.

Command-line exercises
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-Json
Scenario analysis
A 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

▶
Learn PowerShell in Less Than 2 Hours — K12 Engineer
English · objects, Get-Member, Select-Object
▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · objects vs text

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
Visual: Get-Member opens one box and lists its contents.
Narration: Get-Member tells you exactly what you are holding.
Shot 3 · 55–90s
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.
or score ≥ 70% on the Quiz

Module 5 · The Pipeline: streaming and parameter binding

28:00 – 35:00 · Objects flow one at a time; for each object the next command's parameter binder tries ByValue first and ByPropertyName second — knowing this lets you predict whether A | B works before you run it
7 minTrace-Command★★★★★ core
Learning objectives
  • Describe streaming: every command's begin runs first, then objects flow one by one through process, then end.
  • 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 and Trace-Command -Name ParameterBinding to prove which parameter received the object.
  • Fix “The input object cannot be bound …” by reshaping objects with Select-Object calculated properties or by using ForEach-Object.
Prerequisites: Modules 3–4. Importance:★★★★★ (this is the course's core model; Lesson 3 writes functions that accept pipeline input)

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:

  1. Tries ByValue without coercion: is the object already the parameter's type (FileInfo for -InputObject [FileInfo[]])?
  2. Tries ByPropertyName without coercion: does the object have a property named like the parameter or one of its aliases?
  3. Tries ByValue with coercion: can it be converted (anything converts to [string])?
  4. Tries ByPropertyName with coercion.
  5. Nothing matched → “The input object cannot be bound to any parameters for the command …”.

How: three real examples

PipelineParameter that bindsWhy
Get-Item ./data/servers.csv | Get-Content-LiteralPathFileInfo 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-PathA string; -Path [string[]] accepts ByValue.
Get-Process -Id $PID | Stop-Process-InputObjectA Process object matches [Process[]] ByValue.
'pwsh' | Get-Processnone — error-Name accepts only ByPropertyName; a string has no Name property.
[pscustomobject]@{Name='pwsh'} | Get-Process-NameNow 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.

Common misconceptions① “The whole output of A is passed to B once” — objects are passed one at a time. ② “Pipeline binding works like Bash stdin” — B must declare pipeline parameters; native programs receive text lines instead. ③ “If A | B works interactively, any object type works” — binding depends on the object's type and property names. ④ “$_ 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

Get-Item servers.csvwrites 1 FileInfo Parameter binder for Get-Content 1 ByValue, no coercion: none accepts FileInfo 2 ByPropertyName, no coercion:FileInfo.PSPath → alias of -LiteralPath ✓ 3 ByValue with coercion (skipped) 4 ByPropertyName with coercion (skipped) mandatory check → ProcessRecord() Get-Content-LiteralPath …servers.csv nothing matched?“The input object cannotbe bound …” per object
Figure 5-1: the four binding attempts, in order, for every object that arrives

Diagram: streaming order

1..3 | ForEach-Object Abegin Aprocess A(1) → B(1)process A(2) → B(2)process A(3) → B(3) | ForEach-Object B (streams)output interleaves:A 1, B 1, A 2, B 2, A 3, B 3Select-Object -First 1 canstop upstream early | Sort-Object (blocks)collects everything in processemits only in endmemory grows with input sizeGroup-Object, Measure-Object too
Figure 5-2: most cmdlets stream; sorting and grouping must wait for the last object

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.

Ready.
Real mechanism behind the animation The steps match the phases that 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

CommandPurposeNotes
Get-Help B -Parameter *“Accept pipeline input?” per parameterNeeds downloaded help
(Get-Command B).Parameters.ValuesSame information from metadataSee the Lab
Trace-Command -Name ParameterBinding -Expression { A | B } -PSHostShow every binding decisionVery verbose; read the “BIND PIPELINE” part
A | Select-Object @{n='Path';e={$_.FullName}} | BRename a property so it bindsCalculated property (Module 6)
A | ForEach-Object { B -Param $_.X }Bind explicitly per objectAlways works; slightly slower
-PipelineVariable vKeep an earlier stage's object available as $v laterCommon 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).

Predict first, then run. Which of these work?
'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
Watch streaming: two 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
Make a non-matching object bind: turn server rows into objects with a 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"
Keep an earlier object with -PipelineVariable:
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 it: run the 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.

Command-line exercises
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.

Scenario analysis
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

▶
PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson
English · long-form; includes the pipeline and parameter binding
▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · objects in the pipeline

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–60s
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.
Shot 3 · 60–90s
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.
or score ≥ 70% on the Quiz

Module 6 · Filtering and shaping: Where, Select, Sort, Group, Measure

35:00 – 42:00 · Five cmdlets replace most of grep, cut, sort, uniq -c and awk; they work on property names instead of column numbers, and “filter left” keeps them fast
7 minservers.csv · access.log★★★★★
Learning objectives
  • Filter with Where-Object in 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) before Where-Object, and know the faster .Where() method.
Prerequisites: Modules 4–5. Importance:★★★★★

What: the five shaping cmdlets

CmdletAliasBash equivalentStreams?
Where-Object?, wheregrep, awk '$3 > 5'Yes
Select-Objectselectcut, head, tailYes (-Last and -Unique must collect)
Sort-Objectsort (Windows)sortNo
Group-Objectgroupsort | uniq -cNo
Measure-Objectmeasurewc -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

SlowerFasterWhy
Get-ChildItem -Recurse | Where-Object Extension -eq '.log'Get-ChildItem -Recurse -Filter *.logThe provider filters before objects are created
Get-Process | Where-Object Name -eq pwshGet-Process -Name pwshThe 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).

Common misconceptions① “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

Import-Csv12 rows6 string props Where-ObjectMonitored -eq 'true'8 rows Group-Object Env3 groupsCount · Name · Group Sort-ObjectCount -Descending(blocking) Select-ObjectName, Count,@{n='Servers';e=…} Bash equivalent: tail -n +2 servers.csv | awk -F, '$6=="true"' | cut -d, -f2 | sort | uniq -c | sort -rn … which breaks on the quoted "web,api" field — Import-Csv parses CSV properly Each box keeps objects; only an optional final Format-Table / Export-Csv decides the output form
Figure 6-1: property names instead of column numbers; every stage is still an object stream

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.

Ready.

Command reference

CommandPurposeNotes
Where-Object Env -eq prodSimple filterOperators: -eq -ne -gt -lt -like -match -in -contains (+ c/i prefixes)
Where-Object { … -and … }Complex filter$_ = current object
Select-Object -First 5 Name, IPColumns and rows-Skip, -Last, -Unique
Select-Object -ExpandProperty NameValues instead of objectsSame as (…).Name for most cases
Sort-Object Env, @{e='Name';Descending=$true}Multi-key sortPer-key direction with a hashtable
Group-Object Env -NoElementCounts per valueWithout -NoElement, .Group holds the objects
Measure-Object Length -Sum -Average -MaximumStatistics-Line -Word -Character for text
(…).Where({ }, 'First', 3)Fast in-memory filterModes: 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.

Monitored servers per environment, with names:
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
The quoted comma is handled: find servers with more than one role.
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
Unique names, sorted, three ways:
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
File statistics (note the platform difference for hidden files):
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
Filter left, measured:
(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.

Command-line exercises
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).

Scenario analysis
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

▶
Learn PowerShell in Less Than 2 Hours — K12 Engineer
English · Where-Object, Select-Object, Sort-Object in practice

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: a Bash pipeline full of column numbers next to a PowerShell pipeline with property names.
Narration: name the property; forget column numbers.
Shot 2 · 30–60s
Visual: the 12 → 8 drop when Monitored is compared explicitly; a red flag on '[bool]'false''.
Narration: CSV values are text. Compare explicitly.
Shot 3 · 60–90s
Visual: a funnel at the source (–Filter) vs a sieve at the end (Where-Object).
Narration: filter left, format right.
or score ≥ 70% on the Quiz

Module 7 · Parsing modes, quoting, escaping and wildcards

42:00 – 50:00 · PowerShell reads each part of a line in either expression mode (like a programming language) or argument mode (like a shell); quotes, the backtick and wildcard characters behave differently in each
8 minfiles/ odd names★★★★★
Learning objectives
  • Predict expression mode vs argument mode: why 2+3 prints 5 but Write-Output 2+3 prints 2+3.
  • Choose single quotes (literal), double quotes (expand $var and $( )) and here-strings; know that only $name is expanded, not $obj.Property.
  • Use the backtick escape (`t, `n, `$), -- (end of parameters) and --% (stop parsing) correctly.
  • Handle names with [ ], $, ', `, a leading -, # and & using -LiteralPath and proper quoting.
Prerequisites: Modules 2, 5. Importance:★★★★★ (quoting bugs cause wrong deletes and broken native calls)

What: two parsing modes

ModeStarts when the token begins withBehaves likeExample
Expressiona number, a quote, $, (, @, [, an operatora programming language: operators work, bare words are errors2+3 → 5; 'a' * 3 → aaa
Argumenta command name, then each argumenta shell: bare words are strings, -x is a parameter nameWrite-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

FormVariables $xSubexpressions $( )Backtick escapesUse for
'single'NoNoNo (write '' for a quote)Paths, regexes, anything literal — the default choice
"double"Yes, simple names onlyYesYes: `t `n `$ `"Messages that include values
@' … '@NoNoNoLiteral multi-line text (scripts, JSON templates)
@" … "@YesYesYesMulti-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

  • -Path parameters treat * ? [ ] as wildcards. [draft] notes.md means “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.txt fails. 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 (Windows on Windows, Standard elsewhere) passes empty strings and embedded quotes correctly. --% (stop-parsing) sends the rest of the line to the program unchanged — useful for cmd-style arguments, but it disables variable expansion.
Common misconceptions① “\ 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

Write-Output 2+3 (2+3) 'lit $x' "val $x" "n=$($a.Count)" -LiteralPath ./-WhatIf.txt commandargument modestarts here "2+3"bare word= string 5( ) → expressionmode lit $xsingle quotesno expansion val 42double quotessimple $name n=3$( ) for members,indexes, calls parameter + value./ keeps a leading -from being a parameter Wildcards: -Path '[draft] notes.md' → pattern (matches nothing) · -LiteralPath '[draft] notes.md' → exact name Escape character: ` (backtick) — `t `n `$ `" · end of parameters: -- · stop parsing for native tools: --%
Figure 7-1: each argument is classified separately; parentheses switch back to expression mode

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.

Ready.

Command reference

SyntaxMeaningNotes
'…' / "…"Literal / expanding string'it''s' doubles a single quote
"$( expr )"Subexpression inside a stringMembers, indexes, method calls
@' … '@ / @" … "@Here-stringsOpening marker ends its line; closing marker starts a line
`n `t `$ `" ``Escapes in double quotesBacktick, not backslash
-LiteralPathNo wildcard interpretationAlias -LP, -PSPath
[WildcardPattern]::Escape($s)Escape * ? [ ] for -PathUseful with -like too
--Everything after is an argumentFor names starting with -
--%Stop parsing: pass the rest literally to a native programNo variable expansion after it
$PSNativeCommandArgumentPassingHow arguments are quoted for native programsWindows (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.

The naive way (build paths by string, pass to -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).

The safe way: keep objects and let them bind by 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).

Type the names yourself — quote each one correctly:
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').

Here-string: generate a small report text with values.
$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 --%.

Command-line exercises
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('['))*"
Scenario analysis
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

▶
PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson
English · long-form; includes variables, strings and quoting

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)

Shot 1 · 0–25s
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.
Shot 2 · 25–60s
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.
Shot 3 · 60–90s
Visual: a file “[draft] notes.md”; -Path finds nothing, -LiteralPath finds it.
Narration: brackets are wildcards. Data-driven names always go to -LiteralPath.
or score ≥ 70% on the Quiz

Module 8 · Your first script: .ps1, param(), execution policy and exit codes

50:00 – 60:00 · A script is a .ps1 file with a param() block; how you run it (call operator, dot-sourcing, pwsh -File, pwsh -Command) decides its scope, its location side effects and the exit code a scheduler or CI sees
10 minGet-DataInfo.ps1★★★★★
Learning objectives
  • Write a script with comment-based help, #Requires, [CmdletBinding()] and a param() block with defaults, and use $PSScriptRoot for 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 -File and pwsh -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).
Prerequisites: Modules 1–7. Importance:★★★★★

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

PolicyEffectDefault for
RestrictedNo scripts at all (commands only)Windows PowerShell 5.1 on Windows client
RemoteSignedLocal scripts run; scripts marked as downloaded (Zone.Identifier) need a signaturepwsh on Windows, Windows Server
AllSignedEvery script must be signed by a trusted publisherHigh-security environments
Bypass / UnrestrictedNothing blocked / warns for downloaded scriptsAutomation, 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

InvocationNew process?Script's variables after it endsSet-Location inside the scriptExit code you see
& ./x.ps1 or ./x.ps1NoGone (script scope)Changes your location (location belongs to the runspace)$LASTEXITCODE = value of exit N
. ./x.ps1 (dot-source)NoKept in your scopeChanges your locationSame
pwsh -File ./x.ps1YesGoneIsolatedThe exit N value; 1 if the script throws
pwsh -Command "./x.ps1"YesGoneIsolated0 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.

Common misconceptions① “Running a script never affects my session” — 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

./Get-DataInfo.ps1path given → file Execution policyWindows only #Requiresversion, modules Parse + bind param()defaults, validation Run in script scope$PSScriptRoot set Objects → success stream → callerWrite-Host / Verbose / Warning → other streams exit N → $LASTEXITCODE (in-process) / process exit code Failure points “running scripts is disabled on this system” → execution policy “cannot be run because it contained a #requires statement” → version/module “not recognized as a name of a cmdlet …” → missing ./ (Module 2) “Cannot process command because of missing mandatory parameters” (-NonInteractive) “…is not digitally signed” → downloaded file + RemoteSigned → Unblock-File
Figure 8-1: every step before the body can stop the script with a distinct, searchable message

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.

Ready.

Interactive troubleshooting tree: my script will not run

Command reference

CommandPurposeNotes
Get-ExecutionPolicy -ListPolicy per scopeThe first defined scope from the top wins
Set-ExecutionPolicy -Scope CurrentUser RemoteSignedAllow your local scriptsNo admin needed
Unblock-File ./x.ps1Remove the “downloaded” markOnly after you read the script
& $path @argsCall operatorRequired when the path is in a variable or quoted
. ./lib.ps1Dot-source into the current scopeFor libraries and profiles
$PSScriptRoot, $PSCommandPathScript folder / full pathEmpty at the prompt
exit N, $LASTEXITCODESet / read an exit code$? is only success/failure of the last command
Get-Help ./x.ps1 -FullRead your script's helpHelp 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.

Create the script (VS Code: 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 0
Run it and use its objects:
Set-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.
Usage error and exit code:
./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
Dot-sourcing vs calling: compare what is left in your session.
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]
Write-Host is not output:
$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.

Command-line exercises
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"
Scenario analysis
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

▶
Microsoft PowerShell for Beginners - Video 1 Learn PowerShell — Shane Young
English · running commands and first scripts
▶
Learn PowerShell in Less Than 2 Hours — K12 Engineer
English · scripting basics

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a .ps1 file assembles: help block, #Requires, param(), body, exit.
Narration: help first, then requirements, then parameters.
Shot 2 · 25–60s
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.
Shot 3 · 60–90s
Visual: a scheduled task line with -NoProfile -NonInteractive -File highlighted.
Narration: automation uses -NoProfile, -NonInteractive and -File.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 1 key points: editions and startup, commands and precedence, discovery, objects and formatting, pipeline binding, shaping, quoting, scripts
PowerShell 7.6Copyable

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 LAST

5. 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 v

6. 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 left

7. 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

Write ~/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 codes
about 25 minLocal onlyIntegrates M1–M8

Scenario

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.

The script (M1, M4, M6, M7, M8) — save as ~/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).

Run it:
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
Break something and check the failure path:
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
Run it the way a scheduler would:
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
Acceptance criteria

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

Version facts were checked on 2026-11-24 against Microsoft Learn, the Microsoft Artifact Registry and YouTube oEmbed; command outputs were produced on PowerShell 7.6.10
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Current releasesPowerShell 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.6Bundled 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 improvementsWhat's New in PowerShell 7.6
EditionsSide-by-side installation, separate profile and module paths, different default encodingsDifferences from Windows PowerShell 5.1
Profiles and startupFour profiles, load order, -NoProfile, -NonInteractive, -File vs -Command exit codesabout_Profiles; about_Pwsh; this lesson's runs
Command precedenceAlias → function → cmdlet → external; no current-folder lookup without a pathabout_Command_Precedence
Pipeline bindingByValue / ByPropertyName, without then with coercion; Trace-Command ParameterBinding output reproduced on 7.6.10about_Pipelines; Trace-Command
Parsing and quotingExpression vs argument mode, quoting rules, backtick escapes, --, --%, wildcardsabout_Parsing; about_Quoting_Rules; about_Wildcards
Execution policyPolicies, scopes, defaults; not a security boundaryabout_Execution_Policies
Container imagemcr.microsoft.com/powershell has lts and latest tagsMCR tag list
Sample datasetNew-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 6323C180C2EFF12EActual 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:

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-Help step and -Examples output 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 -List on your machine as the reference.