PowerShell Lesson 4: Modules, Packages, Providers and Cross-Platform Environments

From “three loose functions you dot-source” to “a versioned module that anyone can install”: how PowerShell finds and loads modules, how to build a script module with private helpers and module-scoped state, what a manifest really controls, how PSResourceGet installs and publishes packages, how providers turn the registry and environment into drives, and what breaks when the same script runs on Windows and Linux
PowerShell 7.6 LTS (7.6.10)PSResourceGet 1.2.1Local only · FreeVerified · 2026-11-24
Position in the Learning Path Lesson 1 explained the engine, objects and the pipeline; Lesson 2 the language (types, operators, collections, control flow); Lesson 3 turned commands into advanced functions and created the course project OpsKit v0.1: three functions — Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint — in ~/pslab/OpsKit/Public/*.ps1, loaded by dot-sourcing OpsKit.ps1. That works on your laptop, but it has no version, no boundary between public and private code, and nobody else can install it. This lesson's milestone is OpsKit v0.2: a script module with OpsKit.psd1 + OpsKit.psm1, Public/ and Private/ folders, version 0.2.0, packaged as a .nupkg, published to a local folder repository (~/pslab/repo) and imported by version in a clean session. Lesson 5 adds error handling and Invoke-OpsBackup on top of it (v0.3); Lesson 8 tests and releases v1.0.
Overall Learning Objectives
  • Explain the module kinds (script, binary, manifest), read $env:PSModulePath on any platform with -split [IO.Path]::PathSeparator, and predict which version auto-loading and Import-Module pick — including the in-box Pester 3.4.0 trap on Windows.
  • Build a script module: an .psm1 that dot-sources Public/ and Private/, exports only public functions, and keeps state in module scope ($script:) that callers cannot see.
  • Write a manifest with New-ModuleManifest: RootModule, ModuleVersion, explicit FunctionsToExport (and why wildcards break auto-loading), RequiredModules, PowerShellVersion / CompatiblePSEditions; validate it with Test-ModuleManifest and read its error messages.
  • Use PSResourceGet (Find-, Install-, Save-, Update-, Get-InstalledPSResource) with NuGet version ranges, scopes and repository trust, and compare it with PowerShellGet v2 (Install-Module).
  • Create a local folder repository, package and publish a module (Compress-PSResource / Publish-PSResource), install a pinned version, make installs reproducible with a required-resource file, and know how private feeds (Azure Artifacts, GitHub Packages) differ.
  • Use providers and drives — FileSystem, Env, Variable, Function, Alias, Certificate and Registry — with the same *-Item / *-ItemProperty cmdlets, and create your own drive with New-PSDrive.
  • Write cross-platform code: Join-Path instead of \, case-sensitive file systems, $IsWindows, UTF-8 without BOM vs Windows PowerShell 5.1 encodings (proved with Format-Hex), CRLF vs LF, and $env:PATH separators.
  • Ship OpsKit v0.2: validate, stage, package, publish to ~/pslab/repo, and prove with an acceptance script that a clean pwsh imports exactly version 0.2.0 with exactly three public commands.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassPrepCheck OpsKit v0.1 from Lesson 3 (or recreate it), create ~/pslab/repo, ~/pslab/modules, ~/pslab/out; confirm PSResourceGet 1.2.xSelf-check checklistOpsKit v0.1 warm-up run
100–06ModulesScript / binary / manifest modules; $env:PSModulePath per edition; auto-loading; Get-Module vs -ListAvailable; Import-Module -Force -PassThru; #Requires -Modules; module-qualified names; Pester 3.4.0 trapModule resolver: which module and version load?Pester 3.4 vs 6.2 side by side in ~/pslab/modules
206–13Script moduleOpsKit.psm1; dot-sourcing Public/ + Private/; Export-ModuleMember; default exports; module scope and $script:; & (Get-Module X) { }; InModuleScope previewWhat happens inside Import-ModuleConvert OpsKit v0.1 to OpsKit.psm1
313–21ManifestNew-ModuleManifest; RootModule; ModuleVersion; FunctionsToExport without wildcards; RequiredModules; PowerShellVersion / CompatiblePSEditions; PrivateData.PSData; Test-ModuleManifestManifest processing pipelineWrite OpsKit.psd1 and reproduce six manifest errors
421–28PSResourceGetFind-/Install-/Save-/Update-/Uninstall-PSResource, Get-InstalledPSResource; scopes; NuGet ranges; trust; v2 comparisonFrom -Version range to folder on diskSave Pester and PSScriptAnalyzer into ~/pslab/modules
528–35RepositoriesFolder repositories; Register-PSResourceRepository; Compress- / Publish-PSResource; .nupkg anatomy; pinned installs; -RequiredResourceFile; Azure Artifacts / GitHub PackagesPublish → feed → install → importBuild OpsKit.0.2.0.nupkg in ~/pslab/repo
635–42Providers and drivesGet-PSProvider, Get-PSDrive; Env:, Variable:, Function:, Alias:, Cert:, HKCU:/HKLM:; New-PSDrive; *-Item, *-ItemProperty; provider capabilities; PSPathPath → provider → itemA Lab: drive and read-only registry/cert queries
742–50Cross-platformJoin-Path/Split-Path/[IO.Path]; ~ and .NET; case; $IsWindows; UTF-8 no BOM vs 5.1; -Encoding; Format-Hex; CRLF/LF; $env:PATH; Windows-only cmdletsOne script, Windows vs LinuxByte-level encoding comparison 7.6 vs 5.1
850–60OpsKit v0.2Final layout; Publish-OpsKit.ps1 (validate → stage → pack/publish); install layout; import by version; release rulesRelease pipeline + troubleshooting treePublish 0.2.0 and import it by version
—After ClassCheat sheet · Integrated labTest-OpsKitPackage.ps1: unpack the package the way an install does, import it by version in a clean child pwsh, verify exports, privacy, version and behaviorFinal quiz (12 questions)All eight acceptance checks pass; exit code 0

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Find and load modules; predict the version✓·✓✓···✓$env:PSModulePath, Get-Module -ListAvailable, Import-Module -RequiredVersionM1, M8
Build a script module with private code·✓✓··✓·✓.psm1, Export-ModuleMember, $script:M2
Write and validate a manifest··✓·✓··✓New-ModuleManifest, Test-ModuleManifest, Update-PSModuleManifestM3, M8
Install, save and update packages✓··✓✓···Find-PSResource, Save-PSResource, Install-PSResource -Version '[x,y)'M4
Publish to a repository; reproducible installs··✓✓✓··✓Register-PSResourceRepository, Publish-PSResource, -RequiredResourceFileM5, integrated lab
Navigate providers and drives·✓···✓✓·Get-PSProvider, New-PSDrive, Get-ItemPropertyM6
Write portable paths, encodings and line endings✓····✓✓✓Join-Path, $IsWindows, -Encoding utf8BOM, Format-HexM7
Release a versioned module and prove it works·✓✓·✓··✓Compress-PSResource, clean pwsh -NoProfile, acceptance checksM8, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Advanced functions, parameter validation, pipeline input, scope rules for functionsPrerequisite; this lesson packages functions you already haveLesson 3: Functions, Scope and Advanced Functions
try/catch, terminating errors, -WhatIf/SupportsShouldProcess, loggingError handling is the next layer of OpsKit (v0.3)Lesson 5
Binary modules in C#, class-based modules, DSC resourcesNeed .NET development; rarely written by operations teamsMicrosoft Learn: “Writing a Windows PowerShell module”
Remoting a module to many machines, Import-Module -PSSessionMulti-machine administrationLesson 6
SecretManagement vaults, credentials for private feeds in CIShown only as an overview here; secrets are Lesson 7's topicLesson 7
Pester tests (InModuleScope), PSScriptAnalyzer, code signing, CI release pipelineQuality 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. Modules 2, 3, 5 and 8 build OpsKit v0.2 step by step — do them in order.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
Voice narration
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
Version notes Verified 2026-11-24 on PowerShell 7.6.10 (.NET 10.0.15, Windows) with the bundled Microsoft.PowerShell.PSResourceGet 1.2.1, PowerShellGet 2.2.5 and PackageManagement 1.4.8.1. PowerShell 7.4 and 7.5 reached end of support on 2026-11-10. The PowerShell Gallery's newest Pester was 6.2.0 on the verification date (5.9.1 is the newest 5.x); Windows still ships Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules. PSResourceGet 1.3.0 previews add a second default repository (Microsoft Artifact Registry), platform-aware installs and $PSUserContentPath support; they are not in 7.6's bundled 1.2.1 and are only mentioned. Safety rule of this lesson: nothing is installed into your real CurrentUser/AllUsers scopes unless you choose to — the labs use Save-PSResource -Path ~/pslab/modules and a folder feed in ~/pslab/repo.

Module 0 · Prep: a local package repository folder

Make sure OpsKit v0.1 from Lesson 3 is in ~/pslab/OpsKit (or recreate it below), create the folders this lesson publishes into, and confirm which PSResourceGet you have
Before class ≈ 10 minRuns locally · FreeWrites only inside ~/pslab
Prerequisites
  • Lessons 1–3, or equivalent: you can write an advanced function with [CmdletBinding()] and param(), and you know what dot-sourcing does.
  • PowerShell 7.6 and the dataset in ~/pslab/data from Lesson 1, Module 0 (./New-LabData.ps1 rebuilds it at any time).
  • Internet access to www.powershellgallery.com for Modules 1 and 4 (read-only searches and downloads into ~/pslab/modules). Everything else works offline.

Warm-up: answer from memory (30 seconds)

1. What is the difference between & ./OpsKit.ps1 and . ./OpsKit.ps1 for a file that only defines functions?

The call operator runs it in a child scope, so the functions vanish when the script ends. Dot-sourcing runs it in your scope, so the functions stay. That is why OpsKit v0.1 had to be dot-sourced — and why everything it defines (including helper variables) lands in your session.

2. Which attribute makes Test-OpsEndpoint accept servers from the pipeline by their IP property?

[Parameter(ValueFromPipelineByPropertyName)] on -ComputerName plus [Alias('IP')]: the binder matches the property name IP to the alias (Lesson 1, Module 5).

3. Why does Get-OpsConfig use Import-PowerShellDataFile instead of dot-sourcing the .psd1?

A data file is parsed in restricted language mode: hashtables, arrays, strings and numbers only, no command execution. A manifest (.psd1) is read the same way — keep that in mind in Module 3.

Step 1: check OpsKit v0.1 (or recreate it)

If you finished Lesson 3 you already have these four files. If not, create them now — they are the minimal v0.1 this lesson starts from. The function names and parameters match Lesson 3; the bodies are intentionally short.

# ~/pslab/OpsKit/Public/Get-OpsConfig.ps1
function Get-OpsConfig {
    <#
    .SYNOPSIS
        Reads the OpsKit configuration file (a .psd1 data file; no code is executed).
    #>
    [CmdletBinding()]
    param(
        [string]$Path = (Join-Path $HOME 'pslab' 'data' 'opskit.config.psd1')
    )
    Import-PowerShellDataFile -LiteralPath $Path
}
# ~/pslab/OpsKit/Public/Get-OpsServer.ps1
function Get-OpsServer {
    <#
    .SYNOPSIS
        Returns servers from the OpsKit inventory as typed objects.
    .EXAMPLE
        Get-OpsServer -Environment prod -Name web-*
    #>
    [CmdletBinding()]
    param(
        [ValidateSet('dev', 'staging', 'prod')]
        [string]$Environment,
        [SupportsWildcards()]
        [string]$Name = '*',
        [string]$Path = ((Get-OpsConfig).Inventory -replace '^~', $HOME)
    )
    Import-Csv -LiteralPath $Path |
        Where-Object { (-not $Environment -or $_.Env -eq $Environment) -and $_.Name -like $Name } |
        ForEach-Object {
            [pscustomobject]@{
                PSTypeName = 'OpsKit.Server'
                Name       = $_.Name
                Env        = $_.Env
                Region     = $_.Region
                IP         = $_.IP
                Roles      = $_.Role -split ','
                Monitored  = $_.Monitored -eq 'true'
            }
        }
}
# ~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1
function Test-OpsEndpoint {
    <#
    .SYNOPSIS
        Tests whether a TCP port answers within a timeout.
    .EXAMPLE
        Get-OpsServer -Environment dev | Test-OpsEndpoint -Port 8080
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('IP')]
        [string]$ComputerName,
        [ValidateRange(1, 65535)]
        [int]$Port = 8080,
        [int]$TimeoutMs = 500
    )
    process {
        $client = [System.Net.Sockets.TcpClient]::new()
        try {
            $ok = $client.ConnectAsync($ComputerName, $Port).Wait($TimeoutMs)
        } catch {
            $ok = $false
        } finally {
            $client.Dispose()
        }
        [pscustomobject]@{ ComputerName = $ComputerName; Port = $Port; Reachable = [bool]$ok }
    }
}
# ~/pslab/OpsKit/OpsKit.ps1
# OpsKit v0.1 loader (Hour 3): dot-source every public function into the caller's scope.
# Usage:  . ~/pslab/OpsKit/OpsKit.ps1
foreach ($file in Get-ChildItem -Path (Join-Path $PSScriptRoot 'Public') -Filter *.ps1) {
    . $file.FullName
}
Set-Location ~/pslab
. ~/pslab/OpsKit/OpsKit.ps1
Get-OpsServer -Environment prod | Format-Table Name, Env, IP, Roles, Monitored
Get-Command Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint | Format-Table CommandType, Name, Source, Version
Test-OpsEndpoint -ComputerName 127.0.0.1 -Port 9 -TimeoutMs 300
Name       Env  IP         Roles      Monitored
----       ---  --         -----      ---------
web-01     prod 10.30.1.41 {web}           True
web-02     prod 10.30.1.42 {web}           True
api-01     prod 10.30.1.43 {api}           True
edge-01    prod 10.30.2.51 {web, api}      True
db-01      prod 10.30.1.44 {db}           False
bastion-01 prod 10.30.2.10 {bastion}      False

CommandType Name             Source Version
----------- ----             ------ -------
   Function Get-OpsServer
   Function Get-OpsConfig
   Function Test-OpsEndpoint

ComputerName Port Reachable
------------ ---- ---------
127.0.0.1       9     False

Look at the empty Source and Version columns: dot-sourced functions belong to no module. Nobody can ask “which OpsKit do you have?”, nobody can install it, and Get-Command -Module OpsKit finds nothing. Fixing exactly that is this lesson's job.

Step 2: create this lesson's folders

'repo', 'modules', 'out' | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path ~/pslab $_) -Force } | Out-Null
Copy-Item ~/pslab/OpsKit ~/pslab/tmp/OpsKit-v0.1 -Recurse     # keep a copy of v0.1
Get-ChildItem ~/pslab -Directory -Name
data
modules
OpsKit
out
repo
scripts
tmp
FolderPurpose in this lesson
~/pslab/repo/A folder repository (NuGet feed on disk): .nupkg files that PSResourceGet can find and install. In a company this would be a file share or an Azure Artifacts / GitHub Packages feed.
~/pslab/modules/A private module folder for Save-PSResource downloads. We add it to $env:PSModulePath only inside the current session, so nothing is installed for your user.
~/pslab/out/Build output: a clean copy of the module that gets packaged (no notes, no tests, no .git).

Step 3: which package manager do you have?

Get-Module Microsoft.PowerShell.PSResourceGet, PowerShellGet, PackageManagement -ListAvailable |
    Format-Table Name, Version, ModuleType
Get-PSResourceRepository
Name                               Version ModuleType
----                               ------- ----------
Microsoft.PowerShell.PSResourceGet 1.2.1       Binary
PackageManagement                  1.4.8.1     Script
PowerShellGet                      2.2.5       Script
PackageManagement                  1.0.0.1     Binary
PowerShellGet                      1.0.0.1     Script

Name      Uri                                      Trusted Priority IsAllowedByPolicy
----      ---                                      ------- -------- -----------------
PSGallery https://www.powershellgallery.com/api/v2 False   50       True

PowerShell 7.6 bundles PSResourceGet 1.2.1 (the *-PSResource cmdlets) and the old PowerShellGet 2.2.5 (Install-Module). The 1.0.0.1 copies come from Windows PowerShell 5.1's folder. Get-PSResourceRepository only reads PSResourceRepository.xml in your local app-data folder; it changes nothing. IsAllowedByPolicy reports whether an administrator's repository allow-list (Group Policy) permits the repository.

Environment self-check checklist

Risks and cleanup The labs write only below ~/pslab. Three commands in this lesson change user state and are marked “optional” where they appear: Register-PSResourceRepository (adds an entry to your repository list), Install-PSResource / Update-PSResource (install into your CurrentUser module folder) and Set-PSResourceRepository. Each has an undo command next to it (Unregister-PSResourceRepository, Uninstall-PSResource). Full cleanup of this lesson: Remove-Item ~/pslab/repo, ~/pslab/modules, ~/pslab/out -Recurse -Force; restore v0.1 with ~/pslab/tmp/OpsKit-v0.1 if you need it.

Module 1 · Modules: kinds, PSModulePath, auto-loading and #Requires -Modules

00:00 – 06:00 · A module is a folder PowerShell can find by name. Where it looks, which version wins, and when it loads decide whether your script gets Pester 6.2 or the Pester 3.4 that ships with Windows
6 minGet-Module · Import-Module★★★★★
Learning objectives
  • Name the three module kinds — script (.psm1), binary (.dll), manifest (.psd1 describing one of the others) — and recognise them in Get-Module output.
  • Read $env:PSModulePath with -split [IO.Path]::PathSeparator, know which entries pwsh 7 adds per edition and platform, and that the folder name must equal the module name.
  • Explain auto-loading, the difference between Get-Module (loaded) and Get-Module -ListAvailable (installed), and use Import-Module -Force -PassThru, -RequiredVersion and #Requires -Modules.
  • Avoid two version traps verified on 7.6.10: the in-box Pester 3.4.0 and swapping versions of a module that loads a .NET assembly in the same session.
Prerequisites: Module 0; Lesson 1 Module 2 (command precedence). Importance:★★★★★ (“works on my machine” for modules is almost always a path or version question)

What: three kinds of module

KindRoot fileContainsExample on 7.6.10
Script moduleName.psm1PowerShell functions, variables, aliases; loaded by running the .psm1 in its own module scopePSReadLine 2.4.5 (script wrapper + dll), Pester, your OpsKit
Binary moduleName.dllCompiled cmdlets (.NET classes)Microsoft.PowerShell.PSResourceGet 1.2.1 (RootModule = './Microsoft.PowerShell.PSResourceGet.dll'), Microsoft.PowerShell.ThreadJob
Manifest moduleName.psd1A data file that describes the module: version, root/nested modules, exports, requirements. ModuleType shows Manifest when there is no single script or binary rootCimCmdlets, Microsoft.PowerShell.Utility, Microsoft.PowerShell.Archive

Almost every real module has a manifest and a root module. ModuleType reports the kind of the root: OpsKit with RootModule = 'OpsKit.psm1' imports as Script.

Why: modules are found by name through PSModulePath

Import-Module OpsKit and auto-loading search every folder in $env:PSModulePath for a subfolder named OpsKit containing OpsKit.psd1, OpsKit.psm1 or OpsKit.dll — either directly or in a version subfolder such as OpsKit/0.2.0/. pwsh 7 builds the variable at startup:

#Windows (pwsh 7.6)Linux / macOSPurpose
1$HOME\Documents\PowerShell\Modules~/.local/share/powershell/ModulesCurrentUser installs
2$env:ProgramFiles\PowerShell\Modules/usr/local/share/powershell/ModulesAllUsers installs
3$PSHOME\Modules$PSHOME/ModulesModules shipped with pwsh — don't touch
4–5…\WindowsPowerShell\Modules, System32\WindowsPowerShell\v1.0\Modules—Windows PowerShell 5.1 folders, appended for compatibility (this is where Pester 3.4.0 lives)

The separator is ; on Windows and : on Linux/macOS — always split with [IO.Path]::PathSeparator. Windows PowerShell 5.1 uses Documents\WindowsPowerShell\Modules instead of #1, which is why a module installed from 5.1 is “missing” in pwsh (Lesson 1, Module 1).

How: auto-loading and explicit imports

  1. You type a command that no loaded module provides. PowerShell looks through the modules on PSModulePath, reading each manifest's export list (cached), finds the module that exports the name, imports it, and runs the command.
  2. If several versions are installed, Import-Module Name and auto-loading search the entries in order and take the highest version from the first entry that contains the module — a newer version in a later entry is ignored (verified on 7.6.10: Pester 5.9.1 in an earlier folder beat 6.2.0 in a later one); -RequiredVersion, -MinimumVersion, -MaximumVersion pin it.
  3. Get-Module lists what is loaded in this session; Get-Module -ListAvailable lists what is installed on PSModulePath (it does not import anything).
  4. Import-Module X does nothing if X is already loaded — -Force re-runs it. -PassThru returns the module object so you can see what you got.
  5. $PSModuleAutoLoadingPreference = 'None' disables auto-loading in a session; #Requires -Modules lets a script refuse to start unless a module (and version) is available.

When: module-qualified names

Microsoft.PowerShell.Utility\Get-Date runs the command from that module even if a function or alias shadows it, and auto-loads the module. In 7.6 the thread-job module was renamed to Microsoft.PowerShell.ThreadJob; the old qualified name ThreadJob\Start-ThreadJob now fails (verified below). Qualified names are precise — and therefore break when a module is renamed.

Common misconceptions① “Get-Module shows what's installed” — it shows what's loaded; add -ListAvailable. ② “Import-Module Pester gives me the latest Pester” — on a stock Windows machine it gives 3.4.0 from the Windows PowerShell folder, which has none of the Pester 5/6 syntax. ③ “Import-Module -Force swaps any version” — not if the old version already loaded a .NET assembly; start a new session. ④ “Copying a module folder anywhere works” — only folders on PSModulePath are found by name, and the folder name must match the module name. ⑤ “Auto-loading means I never need imports” — scripts should state their dependencies with #Requires -Modules or explicit Import-Module.

Architecture diagram: from a command name to a loaded module

Get-OpsServernot loaded yet $env:PSModulePath (in order)1 Documents\PowerShell\Modules · 2 Program Files3 $PSHOME\Modules · 4–5 WindowsPowerShell <entry>\OpsKit\0.2.0\OpsKit.psd1folder name = module nameversion folders side by side Read manifest (data only)FunctionsToExport contains the name?highest version unless pinned Import: run OpsKit.psm1in a new module scopeexport the public functions Command runs · Get-Module now lists OpsKit · Get-Command shows Source = OpsKit, Version = 0.2.0Shortcut or override: Import-Module -RequiredVersion · #Requires -Modules · Module\Command · $PSModuleAutoLoadingPreference
Figure 1-1: auto-loading reads manifests, not code — which is why the manifest's export list matters so much in Module 3

Version selection: same name, three folders

~/pslab/modules (prepended)Pester\6.2.0Pester\5.9.1 $PSHOME\Modulesno PesterPSResourceGet 1.2.1, PSReadLine 2.4.5 WindowsPowerShell\ModulesPester\3.4.0 (ships with Windows)PSReadLine 2.0.0 Import-Module Pester → 6.2.0 (highest version in the first folder that has Pester) Import-Module Pester -RequiredVersion 5.9.1 → 5.9.1 (only in a fresh session once 6.2.0's Pester.dll is loaded) without ~/pslab/modules on the path → 3.4.0 (the classic trap)
Figure 1-2: the first PSModulePath folder that contains the module decides, then its highest version wins — so the order of the folders defines your behavior

Module resolver: which module and which version load?

Pick a situation and step through what PowerShell checks. All final outputs were reproduced on 7.6.10.

Ready.
Real mechanism behind the animation Command discovery first checks loaded commands (Lesson 1, Module 2). If nothing matches and auto-loading is on, PowerShell enumerates modules on PSModulePath using a per-user module analysis cache of each module's exported names, imports the first module that exports the name, and retries. #Requires -Modules is evaluated before the first line of the script runs; .NET assemblies loaded by a module stay in the process until it exits.

Command table

CommandPurposeNotes
$env:PSModulePath -split [IO.Path]::PathSeparatorWhere modules are searchedPortable split (; / :)
Get-ModuleLoaded modulesSession only
Get-Module Name -ListAvailableInstalled modules, all versionsDoes not import
Import-Module Name -PassThruImport and return the module objectSee Version, ModuleBase
Import-Module Name -ForceRe-run the moduleUse after editing a module; cannot unload assemblies
Import-Module Name -RequiredVersion 5.9.1Exact versionAlso -MinimumVersion, -MaximumVersion
Remove-Module NameUnload commands from the sessionAssemblies stay loaded
#Requires -Modules @{ ModuleName='X'; ModuleVersion='5.0.0' }Script prerequisiteModuleVersion = minimum; RequiredVersion = exact
Module\CommandModule-qualified callBypasses shadowing; auto-loads
$PSModuleAutoLoadingPreferenceAll (default), ModuleQualified, NoneDiagnostics; rarely in production
$env:PSModulePath -split [IO.Path]::PathSeparator
C:\Users\labadmin\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\7\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

Entries 4 and 5 come from the machine-level variable that Windows PowerShell uses; pwsh prepends its own three. If your output has duplicates, someone stored pwsh's paths in the machine-level variable — harmless but confusing.

Get-Module | Format-Table Name, ModuleType, Version
$null = Get-PSResourceRepository            # a command from a module that is not loaded
Get-Module | Format-Table Name, ModuleType, Version
Name                            ModuleType Version
----                            ---------- -------
Microsoft.PowerShell.Management   Manifest 7.0.0.0
Microsoft.PowerShell.Utility      Manifest 7.0.0.0

Name                               ModuleType Version
----                               ---------- -------
Microsoft.PowerShell.Management      Manifest 7.0.0.0
Microsoft.PowerShell.PSResourceGet     Binary 1.2.1
Microsoft.PowerShell.Utility         Manifest 7.0.0.0

How to verify: the binary module appeared only after its command ran — that is auto-loading. Common mistake: concluding “not installed” from plain Get-Module.

$roots = $env:PSModulePath -split [IO.Path]::PathSeparator
Get-Module -ListAvailable PSReadLine, Microsoft.PowerShell.PSResourceGet, Pester, CimCmdlets,
                          Microsoft.PowerShell.Archive, Microsoft.PowerShell.ThreadJob |
    Format-Table Name, Version, ModuleType, @{ n = 'Root#'; e = {
        $b = $_.ModuleBase; 1 + [array]::FindIndex([string[]]$roots, [Predicate[string]]{ param($r) $b -like "$r*" }) } }
Name                               Version ModuleType Root#
----                               ------- ---------- -----
CimCmdlets                         7.0.0.0   Manifest     3
Microsoft.PowerShell.Archive       1.2.7     Manifest     3
Microsoft.PowerShell.PSResourceGet 1.2.1       Binary     3
Microsoft.PowerShell.ThreadJob     2.2.0       Binary     3
PSReadLine                         2.4.5       Script     3
Pester                             3.4.0       Script     4
PSReadLine                         2.0.0       Script     4

Root# is the PSModulePath entry the module was found in. PSReadLine is installed twice; pwsh loads 2.4.5 because $PSHOME\Modules comes first. Pester exists only as 3.4.0 in Windows PowerShell's folder.

# The Pester trap, then the fix: a newer Pester in a folder you control
Import-Module Pester
(Get-Module Pester).Version.ToString()
@(Get-Command Should-Be -ErrorAction SilentlyContinue).Count
./scripts/needs-pester.ps1          # starts with: #Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' }
3.4.0
0
The script 'needs-pester.ps1' cannot be run because the following modules that are specified by the "#requires" statements of the script are missing: The module 'Pester' cannot be found with ModuleVersion '5.0.0'..
# (after Module 4 saved Pester 5.9.1 and 6.2.0 into ~/pslab/modules) — new session:
$env:PSModulePath = (Join-Path $HOME 'pslab' 'modules') + [IO.Path]::PathSeparator + $env:PSModulePath
Get-Module Pester -ListAvailable | Format-Table Name, Version
Import-Module Pester -PassThru | Format-Table Name, Version, ModuleType
Get-Command Should-Be | Format-Table CommandType, Name, Version, Source
./scripts/needs-pester.ps1
Name   Version
----   -------
Pester 6.2.0
Pester 5.9.1
Pester 3.4.0

Name   Version ModuleType
----   ------- ----------
Pester 6.2.0       Script

CommandType Name      Version Source
----------- ----      ------- ------
   Function Should-Be 6.2.0   Pester

Pester 6.2.0 is loaded
# ...and in the same session try to switch back to 5.9.1
Import-Module Pester -RequiredVersion 5.9.1 -Force
Add-Type: Could not load file or assembly 'Pester, Version=5.9.1.0, Culture=neutral, PublicKeyToken=null'. Assembly with same name is already loaded
Method invocation failed because [Pester.Factory] does not contain a method named 'CreateRuntimeDefinedParameterDictionary'.
…
Import-Module: Should operator 'Be' is not registered

How to verify: (Get-Module Pester).Version afterwards still says 6.2.0. Common mistake: trusting -Force to swap versions. Production use: pin versions per process — CI jobs start a fresh pwsh and import with -RequiredVersion (or a #Requires with RequiredVersion).

Get-Command Start-ThreadJob | Format-Table CommandType, Name, Version, Source
ThreadJob\Start-ThreadJob -ScriptBlock { 1 }
Microsoft.PowerShell.ThreadJob\Start-ThreadJob -ScriptBlock { 1 } | Receive-Job -Wait -AutoRemoveJob
$PSModuleAutoLoadingPreference = 'None'
Get-PSResourceRepository
CommandType Name            Version Source
----------- ----            ------- ------
     Cmdlet Start-ThreadJob 2.2.0   Microsoft.PowerShell.ThreadJob

ThreadJob\Start-ThreadJob: The module 'ThreadJob' could not be loaded. For more information, run 'Import-Module ThreadJob'.
1
Get-PSResourceRepository: The term 'Get-PSResourceRepository' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Goal: See auto-loading, the Pester trap and #Requires with your own eyes. Environment: pwsh 7.6 on Windows (on Linux/macOS there is no Pester 3.4 — you will simply see “no Pester”). Safety: read-only, plus one small script in ~/pslab/scripts. Cost: none.

List the search path and count installed modules per root:
$roots = $env:PSModulePath -split [IO.Path]::PathSeparator
$roots
Get-Module -ListAvailable | Group-Object { $m = $_; ($roots | Where-Object { $m.ModuleBase -like "$_*" } | Select-Object -First 1) } -NoElement

The counts depend on what you have installed; on the lab machine the Windows PowerShell folder held most modules (Az was installed for 5.1).

Watch auto-loading in a clean child process:
pwsh -NoProfile -Command 'Get-Module | ForEach-Object Name; "--"; $null = Get-PSResourceRepository; Get-Module | ForEach-Object Name'
Reproduce the Pester trap: create the script and run it.
Set-Content ~/pslab/scripts/needs-pester.ps1 -Value @'
#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' }
"Pester $((Get-Module Pester).Version) is loaded"
'@
pwsh -NoProfile -Command 'Import-Module Pester; (Get-Module Pester).Version.ToString()'
pwsh -NoProfile -File ~/pslab/scripts/needs-pester.ps1; "exit=$LASTEXITCODE"
3.4.0
The script 'needs-pester.ps1' cannot be run because the following modules that are specified by the "#requires" statements of the script are missing: The module 'Pester' cannot be found with ModuleVersion '5.0.0'..
exit=1
Module-qualified names: call Microsoft.PowerShell.Utility\Get-Date -Format yyyy-MM-dd, then define function Get-Date { 'shadowed' } and call both forms. Remove the function with Remove-Item Function:\Get-Date.
Cleanup: nothing to clean — keep needs-pester.ps1; Module 4 makes it pass.

Case 1: CI runs the wrong test framework

Problem: A pipeline step ran Invoke-Pester on a self-hosted Windows agent; tests written for Pester 5 failed with odd syntax errors, although “Pester is installed”. Root cause: the agent only had the in-box Pester 3.4.0; auto-loading picked it. Fix: save the required Pester into a build-local folder (Save-PSResource -Path ./modules), prepend it to $env:PSModulePath in the job, and Import-Module Pester -RequiredVersion …; add #Requires -Modules to the test runner. Lesson: “installed” is meaningless without a version.

Case 2: a long-lived automation host stuck on an old module

Problem: A runbook worker updated a module, but jobs kept failing with the old behaviour, even after Import-Module -Force. Root cause: the module ships a .NET assembly; the first version's assembly stayed loaded in the worker process. Fix: run jobs in fresh processes (or recycle the worker) after updates; pin the version in the job. Reproduced above with Pester 6.2.0 → 5.9.1.

Case 3: a renamed module breaks qualified calls

Problem: After moving scripts to 7.6, ThreadJob\Start-ThreadJob failed while Start-ThreadJob worked. Root cause: the module is now Microsoft.PowerShell.ThreadJob. Fix: update qualified names; use qualified names only where shadowing is a real risk.

Common errors and fixes

Import-Module: The specified module 'X' was not loaded because no valid module file was found in any module directory.

Cause: no folder named X on PSModulePath, a typo, or the module is installed for the other edition.

$env:PSModulePath -split [IO.Path]::PathSeparator
Get-Module X -ListAvailable
Get-ChildItem ($env:PSModulePath -split [IO.Path]::PathSeparator) -Directory -Filter X* -ErrorAction Ignore

Fix: import by path, or put the module in a folder named exactly like the module on PSModulePath.

Tests fail with old syntax / Should-Be not found although Pester is installed

Cause: Pester 3.4.0 (Windows in-box) was loaded.

(Get-Module Pester).Version; Get-Module Pester -ListAvailable

Fix: provide Pester 6.x (or 5.x) on PSModulePath and import it with -RequiredVersion or -MinimumVersion.

Assembly with same name is already loaded

Cause: a different version of the module's dll is already in the process.

Fix: start a new pwsh; import the wanted version first.

The script 'x.ps1' cannot be run because the following modules that are specified by the "#requires" statements of the script are missing

Cause: the module or the minimum version is not on PSModulePath. The script did not start at all — nothing ran.

Fix: install/save the version, or relax the requirement deliberately.

Command-line exercises
1. Show every installed version of PSReadLine with the folder it lives in.
Get-Module PSReadLine -ListAvailable | Format-Table Name, Version, ModuleBase
2. Write a script header that refuses to run unless Pester 5.9.1 exactly is available.
#Requires -Modules @{ ModuleName = 'Pester'; RequiredVersion = '5.9.1' }

ModuleVersion means “at least”; RequiredVersion means “exactly”; MaximumVersion also exists.

Scenario analysis
A colleague says “Get-Module shows no Az module, so Az isn't installed — I'll install it again for all users.” What do you check first?

Get-Module lists loaded modules only. Check Get-Module Az.Accounts -ListAvailable and the PSModulePath entries; Az may be installed for Windows PowerShell 5.1 (visible to pwsh via entries 4–5) or for another user. Reinstalling for AllUsers creates a second copy and a new “which version wins” problem. Decide on one scope and one version, and pin it in scripts.

Verified teaching videos

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · fundamentals including finding and using modules (title and channel verified)
▶
PowerShell 7 Overview — John Savill's Technical Training
English · PowerShell 7 vs Windows PowerShell, side-by-side install (title and channel verified)

No verified video covers the Pester 3.4 trap or assembly reloading; use this module's reproductions.

Official documentation

Video storyboard (about 90 seconds)

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

Shot 1 · 0–20s
Visual: a command name drops into a funnel labelled PSModulePath; five folders light up in order.
Narration: modules are folders found by name, in PSModulePath order.
Shot 2 · 20–45s
Visual: three Pester folders (6.2.0, 5.9.1, 3.4.0); remove the first folder from the path and 3.4.0 wins.
Narration: highest version on the path wins — and Windows ships Pester 3.4.
Shot 3 · 45–70s
Visual: Import-Module -Force bounces off a locked “Pester.dll” box.
Narration: assemblies stay loaded; switch versions in a new process.
Shot 4 · 70–90s
Visual: a script with a #Requires line stops at the door with a red sign.
Narration: declare what you need; fail before line one, not halfway.
or score ≥ 70% on the Quiz

Module 2 · Building a script module: .psm1, Public / Private and module scope

06:00 – 13:00 · One .psm1 that dot-sources one file per function, exports only the public ones, and keeps shared state in module scope where callers cannot reach it
7 minOpsKit.psm1★★★★★
Learning objectives
  • Turn OpsKit v0.1 into a script module: OpsKit.psm1 + Public/*.ps1 + Private/*.ps1, imported with Import-Module instead of dot-sourcing.
  • Control the public surface with Export-ModuleMember, and know the defaults without it (verified: all functions exported, variables and aliases not).
  • Use module scope: $script: variables in a module are shared by all its functions and invisible to the caller; peek inside with & (Get-Module OpsKit) { … } (Pester's InModuleScope in Lesson 8).
  • Reload correctly during development with Import-Module -Force.
Prerequisites: Module 1; Lesson 3 (advanced functions, scopes). Importance:★★★★★

What: a script module is a .psm1 run in its own scope

When you import OpsKit.psm1, PowerShell creates a module session state — a private scope tree just for the module — and runs the file there. Everything the file defines lives in that scope. Then the module exports some of those things into the caller's session. Your functions still run in the module's scope when called, so they see the module's $script: variables and private helpers.

v0.1: . ./OpsKit.ps1 (dot-source)v0.2: Import-Module OpsKit
Where functions liveYour session's scope (global if at the prompt)The module's own session state
Helper functionsVisible to everyone, can be overwritten by accidentPrivate unless exported
Shared variablesPollute your session ($file leaks)$script: in module scope, invisible outside
Get-Command x → SourceemptyOpsKit
UnloadDelete each functionRemove-Module OpsKit
Versioned, installableNoYes, once it has a manifest (Module 3)

Why: one file per function, Public / Private

The common layout used by most open-source modules: Public/ holds one file per exported command (file name = function name), Private/ holds helpers, and the .psm1 is a short loader. Reviews and merges touch one small file; the loader can derive the export list from the file names. The cost: dot-sourcing many files at import time is slightly slower than one big .psm1 — Lesson 8 shows how a build step can merge them for release.

How: the loader

# OpsKit.psm1 - root module of OpsKit v0.2
# Module-scoped state ($script:) is shared by every OpsKit function and invisible to callers.
$script:DefaultConfigPath = Join-Path $HOME 'pslab' 'data' 'opskit.config.psd1'
$script:ConfigCache       = $null
$script:ConfigCachePath   = $null

# Load private helpers first, then the public functions (one function per file).
$private = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Private') -Filter *.ps1 -ErrorAction Stop)
$public  = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Public')  -Filter *.ps1 -ErrorAction Stop)
foreach ($file in $private + $public) {
    try {
        . $file.FullName
    } catch {
        throw "OpsKit: cannot load $($file.FullName): $_"
    }
}

# Only the public functions leave the module. The manifest (OpsKit.psd1) repeats this list.
Export-ModuleMember -Function $public.BaseName
  • $PSScriptRoot is the module folder, wherever it is installed — never use the current location.
  • . $file.FullName inside the .psm1 defines the functions in module scope; that's why dot-sourcing is right here and wrong in your profile-free scripts.
  • Private files load first so that public functions can use them at import time if needed.
  • Export-ModuleMember -Function $public.BaseName exports by file name — a function whose name differs from its file name would silently stay private (a review rule: file name = function name).
  • If the .psm1 calls Export-ModuleMember at all, only what it names is exported. Without it, every function is exported, but no variables and no aliases (verified below).

When: module scope vs global scope

Write inside a module functionEffect
$x = 1Local to that function call
$script:x = 1Module-wide state (cache, connection, settings) — shared by all OpsKit functions, survives between calls, gone on Remove-Module
$global:x = 1Leaks into the user's session — avoid; it is how modules break each other
Common misconceptions① “The .psm1 runs in my scope like a dot-sourced script” — it runs in the module's own session state. ② “No Export-ModuleMember means nothing is exported” — all functions are exported (helpers too); variables and aliases are not. ③ “$script: in a module means the calling script's scope” — it means the module's scope. ④ “Edit a file and run the command again” — the old definition stays until Import-Module -Force. ⑤ “Private functions are a security boundary” — they are hidden from discovery, not protected: & (Get-Module OpsKit) { ConvertTo-OpsServer … } can still call them.

Architecture diagram: OpsKit v0.2 as a script module

~/pslab/OpsKit/ OpsKit.psd1 (Module 3)OpsKit.psm1 (loader) Public/Get-OpsConfig.ps1Get-OpsServer.ps1Test-OpsEndpoint.ps1 Private/ConvertTo-OpsServer.ps1Resolve-OpsPath.ps1 Import-Module Module session state (OpsKit) $script:ConfigCache$script:DefaultConfigPath public functionsGet-OpsConfig · Get-OpsServerTest-OpsEndpoint private helpersConvertTo-OpsServerResolve-OpsPath export Your sessionGet-OpsConfigGet-OpsServerTest-OpsEndpointno helpers, no $script:Source = OpsKit
Figure 2-1: the module scope is a box with one door — the export list. Functions called through the door still run inside the box

What happens inside Import-Module

Step through the import of OpsKit and what the caller can see afterwards.

Ready.
Real mechanism behind the animation Import-Module creates a PSModuleInfo with its own SessionState, runs the root module in it, collects exported functions (filtered by Export-ModuleMember, then by the manifest's *ToExport lists), and imports those into the caller's session state. A function remembers the session state it was defined in; calling it switches into that module scope.

Command table

CommandPurposeNotes
Import-Module ~/pslab/OpsKitImport by folder pathFinds OpsKit.psd1 or OpsKit.psm1 in the folder
Import-Module ./OpsKit.psm1 -Force -PassThru(Re)load and show the moduleUse after every edit
Export-ModuleMember -Function a, b -Variable v -Alias xDefine the public surfaceOnly in a .psm1
Get-Command -Module OpsKitWhat the module exportsTriggers import if needed
(Get-Module OpsKit).ExportedFunctionsSame, from the module object
& (Get-Module OpsKit) { $script:ConfigCache }Run code inside the module scopeDebugging only; Pester: InModuleScope OpsKit { }
Remove-Module OpsKitUnloadModule state is discarded

The private helpers and the two refactored public functions

# ~/pslab/OpsKit/Private/Resolve-OpsPath.ps1
function Resolve-OpsPath {
    # Private: expands a leading ~ so paths from the config file work on every platform.
    param([Parameter(Mandatory)][string]$Path)
    if ($Path -match '^~(?=$|[\\/])') {
        $Path = $HOME + $Path.Substring(1)
    }
    $Path
}
# ~/pslab/OpsKit/Private/ConvertTo-OpsServer.ps1
function ConvertTo-OpsServer {
    # Private: turns one servers.csv row (every value a string) into a typed OpsKit.Server object.
    param([Parameter(Mandatory, ValueFromPipeline)]$Row)
    process {
        [pscustomobject]@{
            PSTypeName = 'OpsKit.Server'
            Name       = $Row.Name
            Env        = $Row.Env
            Region     = $Row.Region
            IP         = $Row.IP
            Roles      = $Row.Role -split ','
            Monitored  = $Row.Monitored -eq 'true'
        }
    }
}
# ~/pslab/OpsKit/Public/Get-OpsConfig.ps1  (v0.2: cached in module scope)
function Get-OpsConfig {
    <#
    .SYNOPSIS
        Reads the OpsKit configuration file (a .psd1 data file; no code is executed).
    .DESCRIPTION
        The result is cached in module scope; -Force reads the file again.
    #>
    [CmdletBinding()]
    param(
        [string]$Path = $script:DefaultConfigPath,
        [switch]$Force
    )
    if ($Force -or $null -eq $script:ConfigCache -or $script:ConfigCachePath -ne $Path) {
        Write-Verbose "OpsKit: reading $Path"
        $script:ConfigCache     = Import-PowerShellDataFile -LiteralPath (Resolve-OpsPath $Path)
        $script:ConfigCachePath = $Path
    }
    $script:ConfigCache
}
# ~/pslab/OpsKit/Public/Get-OpsServer.ps1  (v0.2: uses the private helpers)
function Get-OpsServer {
    <#
    .SYNOPSIS
        Returns servers from the OpsKit inventory as typed objects.
    .EXAMPLE
        Get-OpsServer -Environment prod -Name web-*
    #>
    [CmdletBinding()]
    param(
        [ValidateSet('dev', 'staging', 'prod')]
        [string]$Environment,
        [SupportsWildcards()]
        [string]$Name = '*',
        [string]$Path
    )
    if (-not $Path) { $Path = (Get-OpsConfig).Inventory }
    Import-Csv -LiteralPath (Resolve-OpsPath $Path) |
        Where-Object { (-not $Environment -or $_.Env -eq $Environment) -and $_.Name -like $Name } |
        ConvertTo-OpsServer
}

Test-OpsEndpoint.ps1 is unchanged from v0.1. OpsKit.ps1 (the v0.1 loader) is deleted.

Import-Module ~/pslab/OpsKit/OpsKit.psm1 -Force -PassThru | Format-List Name, ModuleType, Version, Path, ExportedFunctions
Get-Command -Module OpsKit | Format-Table CommandType, Name, Version, Source
Get-OpsServer -Environment dev | Format-Table Name, Env, IP, Roles, Monitored
ConvertTo-OpsServer
Name              : OpsKit
ModuleType        : Script
Version           : 0.0
Path              : C:\Users\labadmin\pslab\OpsKit\OpsKit.psm1
ExportedFunctions : {[Get-OpsConfig, Get-OpsConfig], [Get-OpsServer, Get-OpsServer], [Test-OpsEndpoint,
                    Test-OpsEndpoint]}

CommandType Name             Version Source
----------- ----             ------- ------
   Function Get-OpsConfig    0.0     OpsKit
   Function Get-OpsServer    0.0     OpsKit
   Function Test-OpsEndpoint 0.0     OpsKit

Name   Env IP         Roles Monitored
----   --- --         ----- ---------
web-01 dev 10.10.1.21 {web}      True
api-01 dev 10.10.1.22 {api}      True
db-01  dev 10.10.1.23 {db}      False

ConvertTo-OpsServer: The term 'ConvertTo-OpsServer' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

How to verify: Source is now OpsKit; the private helper is unknown to the caller but works inside Get-OpsServer. Version : 0.0 — a bare .psm1 has no version; Module 3 fixes that.

"caller sees `$script:ConfigCache = [$script:ConfigCache]"
$m = Get-Module OpsKit
& $m { "inside the module: DefaultEnv = $($script:ConfigCache.DefaultEnv); cached from $(Split-Path $script:ConfigCachePath -Leaf)" }
Get-OpsConfig -Verbose | Out-Null          # cached: no file read
Get-OpsConfig -Verbose -Force | Out-Null   # forced reload
caller sees $script:ConfigCache = []
inside the module: DefaultEnv = dev; cached from opskit.config.psd1
VERBOSE: OpsKit: reading C:\Users\labadmin\pslab\data\opskit.config.psd1

Only one VERBOSE line: Get-OpsServer had already filled the cache, so the first Get-OpsConfig read nothing. The caller's $script:ConfigCache is a different variable (the caller's own script scope) and is empty.

Defaults without Export-ModuleMember, and stale definitions

$t = Join-Path ~/pslab/tmp 'Leaky'
$null = New-Item -ItemType Directory -Path $t -Force
Set-Content -LiteralPath (Join-Path $t 'Leaky.psm1') -Value @'
$script:Counter = 0
$Visible = 'module variable'
function Get-LeakyPublic { "public $((Get-LeakyHelper))" }
function Get-LeakyHelper { $script:Counter++; $script:Counter }
Set-Alias -Name glp -Value Get-LeakyPublic
'@
Import-Module $t -Force
Get-Command -Module Leaky | Format-Table CommandType, Name
"Visible = [$Visible]"
Get-LeakyPublic; Get-LeakyPublic
Remove-Module Leaky; Remove-Item -LiteralPath $t -Recurse
Import-Module OpsKit
CommandType Name
----------- ----
   Function Get-LeakyHelper
   Function Get-LeakyPublic

Visible = []
public 1
public 2
Import-Module: The specified module 'OpsKit' was not loaded because no valid module file was found in any module directory.

How to verify: the helper leaked; the alias glp and the variable did not; $script:Counter kept its value between calls. The last line: ~/pslab is not on PSModulePath, so import by path until Module 8 installs it. Common mistake: relying on the default and shipping every helper as a public command. Production use: always export explicitly — in the .psm1 and, more importantly, in the manifest.

# edit TimeoutMs default 500 → 750, then:
Import-Module ~/pslab/OpsKit            # already loaded → nothing happens
(Get-Command Test-OpsEndpoint).ScriptBlock.Ast.Body.ParamBlock.Parameters[-1].DefaultValue.Extent.Text
Import-Module ~/pslab/OpsKit -Force
(Get-Command Test-OpsEndpoint).ScriptBlock.Ast.Body.ParamBlock.Parameters[-1].DefaultValue.Extent.Text
500
750

Goal: Convert OpsKit v0.1 into a script module with one public/private boundary and module-scoped state. Environment: pwsh 7.6, ~/pslab/OpsKit from Module 0 (backup in ~/pslab/tmp/OpsKit-v0.1). Cost: none.

Create the folders and private helpers: New-Item -ItemType Directory ~/pslab/OpsKit/Private -Force, then save Resolve-OpsPath.ps1 and ConvertTo-OpsServer.ps1 from the Commands tab into it.
Refactor two public functions: replace Public/Get-OpsConfig.ps1 and Public/Get-OpsServer.ps1 with the v0.2 versions (cache + helpers).
Write the loader and remove the old one: save OpsKit.psm1 (Principles tab), then Remove-Item ~/pslab/OpsKit/OpsKit.ps1.
Import and inspect in a fresh session (no leftovers from dot-sourcing):
pwsh -NoProfile -Command 'Import-Module ~/pslab/OpsKit/OpsKit.psm1; Get-Command -Module OpsKit | ForEach-Object Name; (Get-OpsServer -Environment prod).Count; [bool](Get-Command Resolve-OpsPath -ErrorAction Ignore)'
Get-OpsConfig
Get-OpsServer
Test-OpsEndpoint
6
False
Prove the cache: run Get-OpsConfig -Verbose twice — only the first call prints VERBOSE: OpsKit: reading …; -Force reads again.
Cleanup: Remove-Module OpsKit. Keep the files — Module 3 adds the manifest.

Case 1: a helper that became an API

Problem: Another team scripted against Format-InternalDate from a shared module. A refactor renamed it and their nightly jobs broke. Root cause: the module had no Export-ModuleMember and no manifest export list, so every helper was public. Fix: explicit exports; anything not exported is free to change. Treat the export list as your API contract and version it (Module 3).

Case 2: two modules fighting over a global variable

Problem: Importing module B changed how module A behaved. Root cause: both stored settings in $global:Config. Fix: $script: state inside each module plus Get-/Set- functions to read and change it.

Case 3: “my fix doesn't work” — but the fix was never loaded

Problem: An engineer edited a function, re-ran the command for half an hour, and saw the old behavior. Root cause: the module was already loaded; Import-Module without -Force was a no-op. Fix: Import-Module … -Force after edits, or test in a fresh pwsh -NoProfile; VS Code users can run the module's test in a new terminal each time.

Common errors and fixes

The term 'Helper' is not recognized … (from inside a module function)

Cause: the private file was not dot-sourced (wrong folder name, file skipped because of a syntax error), or the helper is defined after code that runs at import time.

Import-Module ~/pslab/OpsKit -Force -Verbose
& (Get-Module OpsKit) { Get-Command -CommandType Function | ForEach-Object Name }
OpsKit: cannot load …\Public\X.ps1: …

Cause: a parse or runtime error in one file; the loader re-throws it with the file name.

Fix: open that file; [System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$null, [ref]$errors) lists syntax errors without running it.

A function exists in the module but is not exported

Cause: its file name differs from the function name, so $public.BaseName does not include it — or the manifest's FunctionsToExport omits it (Module 3).

Changes are ignored

Import-Module -Force, or a new session.

Command-line exercises
1. List the functions that exist inside OpsKit's module scope, including private ones.
& (Get-Module OpsKit) { Get-ChildItem Function: | Where-Object { $_.Module.Name -eq 'OpsKit' } | ForEach-Object Name }
2. Export only Get-OpsServer for a quick experiment without editing files.
Import-Module ~/pslab/OpsKit/OpsKit.psm1 -Function Get-OpsServer -Force
Get-Command -Module OpsKit

Import-Module -Function filters what is imported into your session; it cannot add what the module does not export.

Scenario analysis
A module function sets $ConnectionString = … in one function and reads it in another; it “works sometimes”. Explain and fix.

A plain assignment creates a local variable in the first function's scope; the second function only sees it if it happens to be called from inside the first (dynamic scoping). Use $script:ConnectionString for module-wide state, or better, pass the value as a parameter / return it as an object.

Verified teaching videos

▶
PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training
English · advanced functions and scripting techniques that lead into modules (title and channel verified)
▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
English · scripts and functions (title and channel verified)

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: loose functions spill into a session; then the same files snap into a box labelled OpsKit.
Narration: dot-sourcing pours code into your session; a module keeps it in its own box.
Shot 2 · 20–50s
Visual: Public/ and Private/ folders; only Public files pass through a door labelled Export-ModuleMember.
Narration: one file per function; export the public ones by name.
Shot 3 · 50–75s
Visual: a $script:ConfigCache jar inside the box, filled once and reused.
Narration: module scope is shared state that callers can't touch.
Shot 4 · 75–90s
Visual: an edited file with an old copy still running; -Force swaps it.
Narration: after an edit, import with -Force.
or score ≥ 70% on the Quiz

Module 3 · Manifests: New-ModuleManifest, exports, RequiredModules and versions

13:00 – 21:00 · The .psd1 is the module's identity card: version, root module, exports, requirements and gallery metadata. PowerShell reads it as data — before running any of your code
8 minOpsKit.psd1★★★★★
Learning objectives
  • Generate OpsKit.psd1 with New-ModuleManifest and explain RootModule, ModuleVersion, GUID, FunctionsToExport, CmdletsToExport/VariablesToExport/AliasesToExport, RequiredModules, PowerShellVersion, CompatiblePSEditions and PrivateData.PSData.
  • Explain why explicit export lists, never '*' — verified: with FunctionsToExport = '*' and dot-sourced files, auto-loading cannot find the commands at all.
  • Validate with Test-ModuleManifest, bump versions with Update-PSModuleManifest, and read the six typical manifest errors.
Prerequisites: Module 2. Importance:★★★★★

What: the keys that matter

KeyMeaningOpsKit v0.2
RootModuleThe file to load (.psm1, .dll); decides ModuleType'OpsKit.psm1'
ModuleVersionA [version] (2–4 numeric parts). Prerelease labels go in PrivateData.PSData.Prerelease'0.2.0'
GUIDIdentity; generate once, never changefixed GUID
FunctionsToExportExact list of public functions; also read by auto-loading and the gallerythree names
CmdletsToExport, VariablesToExport, AliasesToExportSame for cmdlets, variables, aliases. @() = none@()
RequiredModulesModules that must be present (imported first). Hashtables with ModuleName + ModuleVersion / RequiredVersion / MaximumVersionnone yet
PowerShellVersionMinimum engine version; enforced by 5.1 and 7.x'7.4'
CompatiblePSEditionsCore and/or Desktop; metadata + gallery filter'Core'
NestedModules, ScriptsToProcess, TypesToProcess, FormatsToProcessExtra modules, scripts run in the caller's scope at import, .ps1xml filesnot used
PrivateData.PSDataGallery metadata: Tags, ProjectUri, LicenseUri, ReleaseNotes, Prereleasetags, notes

Why: explicit exports (and no wildcards)

Auto-loading, Get-Module -ListAvailable and the PowerShell Gallery all read the manifest without running the module. If FunctionsToExport lists names, they know the commands instantly. If it is '*', PowerShell has to analyze the .psm1 to guess — and static analysis cannot see functions defined in dot-sourced files. Verified on 7.6.10 with an OpsKit copy on PSModulePath:

explicit  ListAvailable exports: Get-OpsConfig, Get-OpsServer, Test-OpsEndpoint
explicit  Get-Command Get-OpsServer -> OpsKit
explicit  loaded: OpsKit
wildcard  ListAvailable exports:
wildcard  Get-Command Get-OpsServer -> not found
wildcard  loaded: no

With the wildcard the module is invisible to auto-loading, and on big modules the analysis makes discovery slow. The manifest's list and the .psm1's Export-ModuleMember both filter: a function must pass both to be exported.

How: semantic versions for a module

ChangeBumpOpsKit example
Breaking: rename/remove a command or parameter, change output typemajor (1.x → 2.0.0)Renaming -Environment to -Env
New command or parameter, backward compatibleminor (0.2 → 0.3.0)Invoke-OpsBackup in Lesson 5
Bug fix onlypatch (0.2.0 → 0.2.1)Fix ~ expansion

Before 1.0 anything may change (SemVer), but users still pin — so treat minors as “may break” until v1.0 in Lesson 8. A published version is immutable: never re-publish 0.2.0 with different content.

When: RequiredModules vs #Requires vs Import-Module inside the psm1

MechanismUse when
RequiredModules in the manifestYour module needs another module; PowerShell imports it first, and PSResourceGet installs it as a dependency
#Requires -Modules in a scriptA script (not a module) needs modules
Import-Module inside the .psm1Optional/conditional dependencies only — invisible to installers
Common misconceptions① “A manifest is a script” — it is a restricted data file; no variables or commands (except a few like $PSScriptRoot in some keys). ② “FunctionsToExport = '*' is the safe default” — it breaks auto-loading for dot-sourced modules and slows discovery. ③ “Test-ModuleManifest passing means the module imports” — verified: it passed with an unsatisfied RequiredModules and with a forgotten export. ④ “CompatiblePSEditions = 'Core' stops Windows PowerShell” — verified: 5.1 still tried to load OpsKit; PowerShellVersion = '7.4' is what stopped it. ⑤ “ModuleVersion = 'v0.2.0' or '0.2.0-beta' works” — it must be a plain [version].

Flowchart: what Import-Module does with a manifest

OpsKit.psd1parsed as data Validate keystypes, syntax PowerShellVersionedition / host checks RequiredModulesimport each first RootModulerun OpsKit.psm1 Export filterExport-ModuleMember ∩ FunctionsToExport Your session3 commands, v0.2.0 Where it fails (all reproduced on 7.6.10) “not a valid PowerShell module manifest file” → syntax / typo in RootModule · “Cannot convert value "v0.2.0" to type System.Version” “requires a minimum PowerShell version of '7.7'” · “The required module 'Pester' is not loaded” silent: a function missing from FunctionsToExport is simply not exported
Figure 3-1: every check before “RootModule” happens without running your code — that is why the manifest can be read by installers, galleries and auto-loading

Manifest processing pipeline

Ready.

Command table

CommandPurposeNotes
New-ModuleManifest -Path X.psd1 @paramsCreate a manifest with comments for every keyGenerates a GUID if you omit it
Test-ModuleManifest X.psd1Validate syntax, types, referenced filesDoes not import the module
Update-PSModuleManifest X.psd1 -ModuleVersion 0.2.1Change keys in place (PSResourceGet)Keeps other keys
Import-PowerShellDataFile X.psd1Read it as a hashtableGood for scripts and tests
(Get-Module X -ListAvailable).ExportedFunctionsWhat discovery seesEmpty with '*' + dot-sourcing
$manifest = @{
    Path                 = '~/pslab/OpsKit/OpsKit.psd1'
    RootModule           = 'OpsKit.psm1'
    ModuleVersion        = '0.2.0'
    GUID                 = '6f1c3d0a-4b7e-4c2a-9a51-0d7e2b6c4f10'
    Author               = 'PowerShell course'
    CompanyName          = 'pslab'
    Description          = 'OpsKit: inventory, configuration and endpoint checks for the PowerShell course.'
    PowerShellVersion    = '7.4'
    CompatiblePSEditions = 'Core'
    FunctionsToExport    = 'Get-OpsConfig', 'Get-OpsServer', 'Test-OpsEndpoint'
    CmdletsToExport      = @()
    VariablesToExport    = @()
    AliasesToExport      = @()
    Tags                 = 'Operations', 'Inventory', 'Course'
    ProjectUri           = 'https://example.com/pslab/opskit'
    ReleaseNotes         = '0.2.0: packaged as a script module with a manifest.'
}
New-ModuleManifest @manifest
Get-Content ~/pslab/OpsKit/OpsKit.psd1 | Where-Object { $_ -match '^\s*[A-Za-z]+\s*=' }
RootModule = 'OpsKit.psm1'
ModuleVersion = '0.2.0'
CompatiblePSEditions = 'Core'
GUID = '6f1c3d0a-4b7e-4c2a-9a51-0d7e2b6c4f10'
Author = 'PowerShell course'
CompanyName = 'pslab'
Copyright = '(c) PowerShell course. All rights reserved.'
Description = 'OpsKit: inventory, configuration and endpoint checks for the PowerShell course.'
PowerShellVersion = '7.4'
FunctionsToExport = 'Get-OpsConfig', 'Get-OpsServer', 'Test-OpsEndpoint'
CmdletsToExport = @()
AliasesToExport = @()
PrivateData = @{
    PSData = @{
        Tags = 'Operations', 'Inventory', 'Course'
        ProjectUri = 'https://example.com/pslab/opskit'
        ReleaseNotes = '0.2.0: packaged as a script module with a manifest.'

Note: VariablesToExport = @() was written as a comment (# VariablesToExport = @()) by New-ModuleManifest on 7.6.10. A commented key falls back to the default, which for variables is “export what the .psm1 exports” — and our Export-ModuleMember exports no variables, so the result is the same. If you want it explicit, uncomment the line. The file is written as ASCII/UTF-8 with CRLF line endings on Windows.

Test-ModuleManifest ~/pslab/OpsKit/OpsKit.psd1 |
    Format-List Name, Version, ModuleType, RootModule, PowerShellVersion, CompatiblePSEditions, ExportedFunctions
Import-Module ~/pslab/OpsKit -Force -PassThru | Format-Table Name, Version, ModuleType
Name                 : OpsKit
Version              : 0.2.0
ModuleType           : Manifest
RootModule           : OpsKit.psm1
PowerShellVersion    : 7.4
CompatiblePSEditions : {Core}
ExportedFunctions    : {[Get-OpsConfig, Get-OpsConfig], [Get-OpsServer, Get-OpsServer], [Test-OpsEndpoint,
                       Test-OpsEndpoint]}

Name   Version ModuleType
----   ------- ----------
OpsKit 0.2.0       Script

Test-ModuleManifest describes the manifest (type Manifest); after import the module reports the type of its root module (Script) and finally a version.

Six manifest errors, reproduced

# each block edits a copy in ~/pslab/tmp/bad/OpsKit, then runs Test-ModuleManifest and/or Import-Module
# 1. RootModule = 'OpsKit.pms1'          2. ModuleVersion = 'v0.2.0'      3. a missing quote
# 4. FunctionsToExport without Test-OpsEndpoint
# 5. RequiredModules = @(@{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' })   (only 3.4.0 installed)
# 6. PowerShellVersion = '7.7'
--- 1. typo in RootModule
Test-ModuleManifest: The module manifest 'OpsKit.pms1' could not be processed because it is not a valid PowerShell module manifest file. Remove the elements that are not permitted: C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1
Import-Module: The module to process 'OpsKit.pms1', listed in field 'ModuleToProcess/RootModule' of module manifest 'C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1' was not processed because no valid module was found in any module directory.
--- 2. ModuleVersion is not a version
Test-ModuleManifest: The 'ModuleVersion' member is not valid in the module manifest file 'C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1': Cannot convert value "v0.2.0" to type "System.Version". Error: "The input string 'v0' was not in a correct format."
--- 3. syntax error (missing quote)
Test-ModuleManifest: The module manifest 'C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1' could not be processed because it is not a valid PowerShell module manifest file. Remove the elements that are not permitted: At C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1:18 char:25
+ CompatiblePSEditions = 'Core'
+                         ~~~~~
Unexpected token 'Core'
…
--- 4. FunctionsToExport forgets a function
Test-ModuleManifest ok: True
Get-OpsConfig, Get-OpsServer
--- 5. RequiredModules not satisfied
Import-Module: The required module 'Pester' is not loaded. Load the module or remove the module from 'RequiredModules' in the file 'C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1'.
--- 6. PowerShellVersion too high
Import-Module: The version of PowerShell on this computer is '7.6.10'. The module 'C:\Users\labadmin\pslab\tmp\bad\OpsKit\OpsKit.psd1' requires a minimum PowerShell version of '7.7' to run. Verify that you have the minimum required version of PowerShell installed, and then try again.

How to read them: #1's first message names the bad value but blames “elements that are not permitted” — misleading; the Import-Module message is clearer. #3 reports the error on the line after the missing quote (line 18, where the string finally ends) — look one line up. #4 and #5 pass Test-ModuleManifest: it checks the file, not your intent or other modules' versions. #5 says “not loaded” although the real problem is “not found in version ≥ 5.0.0”.

# Windows PowerShell 5.1 importing the 7.4+/Core manifest
powershell.exe -NoProfile -Command "Import-Module $HOME\pslab\OpsKit\OpsKit.psd1"
The version of Windows PowerShell on this computer is '5.1.26100.10068'. The module 'C:\Users\labadmin\pslab\OpsKit\OpsKit.psd1' requires a minimum Windows PowerShell version of '7.4' to run. Verify that you have the minimum required version of Windows PowerShell installed, and then try again.

With PowerShellVersion removed, 5.1 accepted the Core-only manifest and went on to load OpsKit.psm1 (it then stopped only because 5.1's own execution policy blocked scripts on that machine). So PowerShellVersion is the real gate; CompatiblePSEditions is a label used by the gallery and by pwsh's Windows-compatibility checks of modules in the System32 module folder.

# bumping a version without regenerating the file
Copy-Item ~/pslab/OpsKit/OpsKit.psd1 ~/pslab/tmp/OpsKit.copy.psd1
Update-PSModuleManifest -Path ~/pslab/tmp/OpsKit.copy.psd1 -ModuleVersion 0.2.1 -ReleaseNotes '0.2.1: fix ~ expansion'
(Import-PowerShellDataFile ~/pslab/tmp/OpsKit.copy.psd1).ModuleVersion
0.2.1

Goal: Give OpsKit an identity: a valid manifest with version 0.2.0 and an explicit export list, then see what the manifest prevents. Environment: OpsKit from Module 2. Cost: none.

Create the manifest with the splat from the Commands tab (keep the GUID, or omit it to get a new one — then never change it again).
Validate and import:
Test-ModuleManifest ~/pslab/OpsKit/OpsKit.psd1 | Format-List Name, Version, ExportedFunctions
Import-Module ~/pslab/OpsKit -Force -PassThru | Format-Table Name, Version, ModuleType
Get-Command -Module OpsKit | Format-Table Name, Version, Source
Prove “no wildcards”: copy OpsKit to ~/pslab/tmp/exp/wildcard/OpsKit, set FunctionsToExport = '*' there, prepend ~/pslab/tmp/exp/wildcard to $env:PSModulePath in a new session, and compare (Get-Module OpsKit -ListAvailable).ExportedFunctions.Keys and Get-Command Get-OpsServer with the explicit version.
Break it on purpose: in a copy under ~/pslab/tmp/bad/OpsKit, reproduce errors 1, 2, 4 and 6 from the Commands tab and write down which ones Test-ModuleManifest catches.
Cleanup: Remove-Item ~/pslab/tmp/exp, ~/pslab/tmp/bad -Recurse -Force; Remove-Module OpsKit.

Case 1: “the command exists but auto-loading can't find it”

Problem: A team's module worked with Import-Module but its commands never auto-loaded, and the gallery page listed no commands. Root cause: FunctionsToExport = '*' with dot-sourced Public files. Fix: generate the explicit list at build time (Module 8 checks that it matches Public/).

Case 2: a new command shipped but invisible

Problem: Release notes announced Get-OpsHealth; users got “not recognized”. Root cause: the file was added to Public/ but not to FunctionsToExport; Test-ModuleManifest passed. Fix: a build check comparing both lists — reproduced in Module 8.

Case 3: dependency declared in code, not in the manifest

Problem: After installing a module on a new server, the first command failed with “Import-Module: … Az.Accounts not found”. Root cause: the .psm1 called Import-Module Az.Accounts; the manifest had no RequiredModules, so the installer didn't bring it. Fix: declare dependencies in RequiredModules with a version range.

Common errors and fixes

… is not a valid PowerShell module manifest file. Remove the elements that are not permitted …

Cause: syntax error, a command or variable in the data file, or a bad file name in RootModule. Fix: read the “At line:char” part (look one line above), check names; Import-PowerShellDataFile gives a second opinion on syntax.

Cannot convert value "…" to type "System.Version"

Use 2–4 numeric parts. Prerelease: ModuleVersion = '0.3.0' + Prerelease = 'beta1' in PSData.

The required module 'X' is not loaded

Cause: X (in the required version) is not on PSModulePath. Fix: install/save it; check the version constraint in RequiredModules.

requires a minimum PowerShell version of …

Run in pwsh 7.x, or lower PowerShellVersion only if you really test on that version.

Imports fine, but a command is missing
(Import-PowerShellDataFile ~/pslab/OpsKit/OpsKit.psd1).FunctionsToExport
(Get-ChildItem ~/pslab/OpsKit/Public -Filter *.ps1).BaseName
Command-line exercises
1. Print the version and the export list from the manifest without importing the module.
$d = Import-PowerShellDataFile ~/pslab/OpsKit/OpsKit.psd1
"$($d.ModuleVersion): $($d.FunctionsToExport -join ', ')"
2. Add a dependency on Pester 5.x (≥ 5.7, < 6) to a copy of the manifest.
Update-PSModuleManifest -Path ~/pslab/tmp/OpsKit.copy.psd1 -RequiredModules @(@{ ModuleName = 'Pester'; ModuleVersion = '5.7.0'; MaximumVersion = '5.99.99' })

Manifests express ranges with ModuleVersion (min) and MaximumVersion; PSResourceGet's -Version uses NuGet ranges (Module 4).

Scenario analysis
Your module must run on Windows PowerShell 5.1 and pwsh 7 for two years. Which manifest keys do you set and how do you prove it?

PowerShellVersion = '5.1', CompatiblePSEditions = 'Desktop','Core', explicit exports, no 7-only syntax (??, ternary, -Parallel) — and a CI matrix that imports and tests the module in both powershell.exe and pwsh. The manifest only declares; tests prove.

Verified teaching videos

▶
PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training
English · title and channel verified; use it for the surrounding scripting concepts

No verified video specifically covers manifest keys, export lists or the wildcard/auto-loading problem; the documentation below and this module's reproductions are the reference.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: an ID card labelled OpsKit 0.2.0 with fields RootModule, Exports, Requires.
Narration: the manifest is the module's identity card, read as data.
Shot 2 · 20–50s
Visual: auto-loading reads three names instantly; with '*' it opens the box, finds nothing, gives up.
Narration: list your exports; wildcards hide dot-sourced functions.
Shot 3 · 50–75s
Visual: six red error cards flip over, two of them pass Test-ModuleManifest.
Narration: validation catches syntax, not intent.
Shot 4 · 75–90s
Visual: version 0.2.0 → 0.2.1 → 0.3.0 → 1.0.0 with labels fix / feature / breaking.
Narration: versions are promises; never reuse one.
or score ≥ 70% on the Quiz

Module 4 · PSResourceGet: find, install, update and save; version ranges and trust

21:00 – 28:00 · The *-PSResource cmdlets bundled with PowerShell 7.6 replace Install-Module: NuGet version ranges, explicit scopes, repository trust — and Save-PSResource for installs that change nothing on the machine
7 minPSResourceGet 1.2.1★★★★☆
Learning objectives
  • Use Find-PSResource, Install-PSResource, Save-PSResource, Update-PSResource, Uninstall-PSResource and Get-InstalledPSResource, and know their aliases (fdres, isres, svres …).
  • Write NuGet version ranges ([5.0,6.0), [5.7.1, ], exact 5.9.1) and verify what they resolve to — including a 1.2.1 quirk where a range resolved to the lowest matching version.
  • Choose a scope (CurrentUser / AllUsers) or no scope at all (Save-PSResource -Path), and handle repository trust without blindly trusting the PowerShell Gallery.
  • Map PowerShellGet v2 commands to PSResourceGet and know why both exist in 7.6.
Prerequisites: Modules 1–3. Importance:★★★★☆

What: one module, three generations of package management

PackageManagement (OneGet) + PowerShellGet v2PSResourceGet (formerly “PowerShellGet v3”)
CommandsFind-Module, Install-Module, Update-Module, Save-Module, Publish-Module, Register-PSRepositoryFind-, Install-, Update-, Save-, Publish-, Compress-PSResource, Register-PSResourceRepository
ImplementationScript module on top of PackageManagement and a NuGet providerOne binary module (C#), no provider bootstrap
Version syntax-RequiredVersion, -MinimumVersion, -MaximumVersion-Version with NuGet ranges
Bundled withWindows PowerShell 5.1 (1.0.0.1) and pwsh 7.6 (2.2.5) for compatibilitypwsh 7.4+ (7.6: 1.2.1); installable on 5.1
StatusMaintenance onlyActive development (1.3 previews)

Why: version ranges and scopes

-VersionMeaningPester on 2026-11-24
5.9.1Exactly this version5.9.1
5.7Exactly 5.7(.0) — not “5.7 or later”5.7.0
[5.7.1, ]≥ 5.7.1 (minimum inclusive needs the bracket form)8 versions, newest 6.2.0
[5.0, 6.0)≥ 5.0 and < 6.0 — “any 5.x”24 versions, newest 5.9.1
(, 5.0]≤ 5.055 versions
*Any (with Find: list all)82 stable versions
Where it goesWindows (pwsh 7)Linux/macOSNeeds admin
-Scope CurrentUser (default)$HOME\Documents\PowerShell\Modules~/.local/share/powershell/ModulesNo
-Scope AllUsers$env:ProgramFiles\PowerShell\Modules/usr/local/share/powershell/ModulesYes
Save-PSResource -Path XAny folder you choose (build folder, offline media, container layer)No; nothing registered

How: repository trust

PSGallery is registered as untrusted. Installing from an untrusted repository prompts; under -NonInteractive (CI, scheduled tasks) the prompt becomes an error. Options: answer the prompt, pass -TrustRepository for one command, or mark a repository trusted with Set-PSResourceRepository -Name X -Trusted. Microsoft's own guidance is to treat the Gallery as a community source: untrusted by default, an intake for packages that you review and promote into your own trusted feed (Module 5).

When: Install vs Save

  • Install for your workstation and long-lived servers: modules land on PSModulePath, auto-loading works, Get-InstalledPSResource/Update-PSResource manage them.
  • Save for builds, containers, air-gapped servers and labs: download exact versions into a folder you control, prepend it to $env:PSModulePath for that process only. Add -IncludeXml so Get-InstalledPSResource -Path recognises them (verified: without it they are invisible to that cmdlet).
  • Update-PSResource installs the newer version side by side; it does not remove the old one and does not reload your session.
Common misconceptions① “-Version 5.7 means 5.7 or newer” — it means exactly 5.7.0; write [5.7, ]. ② “A range always gets the newest match” — verified on 1.2.1: Save-PSResource PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' saved 1.22.0, the lowest; always check with -PassThru and pin exact versions for reproducibility. ③ “-Version '5.*' means 5.x” — verified: it returned 6.x versions too. ④ “Update-PSResource replaces the old version” — it adds a new folder. ⑤ “-TrustRepository everywhere is fine” — it disables the one prompt that asks whether you meant to pull code from the internet.

Flowchart: from a version range to a folder on disk

Install-PSResource Pester-Version '[5.0, 6.0)' Repositories by Prioritylower number first; first hit wins Resolve rangecheck with -PassThru / Find Trusted?no → prompt / error Download .nupkg (+ dependencies)optional -AuthenticodeCheck Extract to <scope or -Path>\Pester\5.9.1\NuGet metadata removed · PSGetModuleInfo.xml Not imported into your session — Import-Module or a new session picks it up (Module 1 rules)Save-PSResource stops at the extract step in your folder; -AsNupkg keeps the .nupkg instead (a local mirror)
Figure 4-1: the installer only puts files in a version folder; the module system (Module 1) decides what loads

From -Version to a folder on disk

Ready.

Command table

PSResourceGetPowerShellGet v2 equivalentNotes
Find-PSResource -Name X [-Version r] [-Prerelease]Find-ModuleAlso -Tag, -Type Module|Script, -IncludeDependencies
Install-PSResource X -Version r -Scope CurrentUserInstall-Module-TrustRepository, -Reinstall, -AcceptLicense, -AuthenticodeCheck, -PassThru
Save-PSResource X -Path dir [-IncludeXml | -AsNupkg]Save-ModuleNo scope, nothing registered
Update-PSResource XUpdate-ModuleSide by side
Get-InstalledPSResource [X] [-Path dir]Get-InstalledModuleOnly sees packages with PSGetModuleInfo.xml
Uninstall-PSResource X -Version vUninstall-Module
Get-PSResourceRepository, Set-PSResourceRepositoryGet-PSRepository, Set-PSRepositoryStored in PSResourceRepository.xml (per user)
Find-PSResource -Name Pester
Find-PSResource -Name Pester -Version '[6.0.0,]' | Format-Table Name, Version, Prerelease, Repository
Find-PSResource -Name PSScriptAnalyzer, Microsoft.PowerShell.SecretManagement | Format-Table Name, Version, Repository
Name   Version Prerelease Repository Description
----   ------- ---------- ---------- -----------
Pester 6.2.0              PSGallery  Pester provides a framework for running BDD style Tests to execute and validate P…

Name   Version Prerelease Repository
----   ------- ---------- ----------
Pester 6.2.0              PSGallery
Pester 6.1.0              PSGallery
Pester 6.0.1              PSGallery
Pester 6.0.0              PSGallery

Name                                  Version Repository
----                                  ------- ----------
PSScriptAnalyzer                      1.25.0  PSGallery
Microsoft.PowerShell.SecretManagement 1.1.2   PSGallery
foreach ($v in '5.7.1', '5.7', '[5.7.1, ]', '[5.0, 6.0)', '(, 5.0]', '5.*') {
    $r = @(Find-PSResource -Name Pester -Version $v -ErrorAction SilentlyContinue)
    '{0,-12} -> {1,2} match(es); newest {2}' -f $v, $r.Count, ($r | Select-Object -First 1).Version
}
Find-PSResource -Name Pester -Version '[9.0,10.0)'
5.7.1        ->  1 match(es); newest 5.7.1
5.7          ->  1 match(es); newest 5.7.0
[5.7.1, ]    ->  8 match(es); newest 6.2.0
[5.0, 6.0)   -> 24 match(es); newest 5.9.1
(, 5.0]      -> 55 match(es); newest 5.0.0
5.*          -> 28 match(es); newest 6.2.0
Find-PSResource: Package 'Pester' could not be found in any registered repositories.

How to verify: 5.7 is exact; 5.* is not “5.x” (28 = 24 × 5.x + 4 × 6.x). The last error says “could not be found” although Pester exists — the message means “no version matches”. Common mistake: trusting a range without looking at what it resolved to.

# Save: no install, nothing registered. First without trusting the repository, non-interactively:
pwsh -NoProfile -NonInteractive -Command "Save-PSResource -Name Pester -Version '[5.0,6.0)' -Path ~/pslab/modules"
Save-PSResource -Name Pester -Version '[5.0,6.0)' -Path ~/pslab/modules -TrustRepository -PassThru | Format-Table Name, Version, Repository
Save-PSResource -Name Pester -Version 6.2.0 -Path ~/pslab/modules -TrustRepository -IncludeXml
Get-ChildItem ~/pslab/modules/Pester -Name
Get-InstalledPSResource -Path ~/pslab/modules | Format-Table Name, Version, Repository
Save-PSResource: PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.

Name   Version Repository
----   ------- ----------
Pester 5.9.1   PSGallery

5.9.1
6.2.0

Name   Version Repository
----   ------- ----------
Pester 6.2.0   PSGallery

Interactively you would get a “You are installing the modules from an untrusted repository … Are you sure?” prompt instead of the first error. Get-InstalledPSResource lists only 6.2.0 because only that save used -IncludeXml (it writes PSGetModuleInfo.xml); Pester 5.9.1 is still perfectly importable.

# The range quirk: same command shape, opposite result
Find-PSResource -Name PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' | Format-Table Name, Version
Save-PSResource -Name PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' -Path ~/pslab/tmp/sv -TrustRepository -PassThru | Format-Table Name, Version
Save-PSResource -Name PSScriptAnalyzer -Path ~/pslab/tmp/sv -TrustRepository -PassThru | Format-Table Name, Version
Name             Version
----             -------
PSScriptAnalyzer 1.22.0
PSScriptAnalyzer 1.23.0
PSScriptAnalyzer 1.24.0
PSScriptAnalyzer 1.25.0

Name             Version
----             -------
PSScriptAnalyzer 1.22.0

Name             Version
----             -------
PSScriptAnalyzer 1.25.0

How to verify: for PSScriptAnalyzer the range results came back oldest-first and Save took the first (1.22.0); for Pester they came newest-first and Save took 5.9.1. Without a range, the newest (1.25.0) was saved. Production use: resolve ranges once (Find-PSResource … | Select-Object -First 1 after sorting by Version), then install the exact version and record it (Module 5's required-resource file).

Get-Command Install-Module, Install-PSResource, Install-Package | Format-Table CommandType, Name, Version, Source
Get-Alias -Definition *PSResource* | Format-Table Name, Definition
CommandType Name               Version Source
----------- ----               ------- ------
   Function Install-Module     2.2.5   PowerShellGet
     Cmdlet Install-PSResource 1.2.1   Microsoft.PowerShell.PSResourceGet
     Cmdlet Install-Package    1.4.8.1 PackageManagement

Name           Definition
----           ----------
cmres          Compress-PSResource
fdres          Find-PSResource
Get-PSResource Get-InstalledPSResource
gres           Get-InstalledPSResource
isres          Install-PSResource
pbres          Publish-PSResource
svres          Save-PSResource
udres          Update-PSResource
usres          Uninstall-PSResource
# Optional — installs into YOUR CurrentUser module folder (not run on the lab machine):
Install-PSResource -Name Pester -Version 5.9.1 -Scope CurrentUser -TrustRepository -PassThru
Get-InstalledPSResource -Name Pester
Update-PSResource -Name Pester -Version '[5.0,6.0)'
Uninstall-PSResource -Name Pester -Version 5.9.1          # undo
Name   Version Prerelease Repository Description
----   ------- ---------- ---------- -----------
Pester 5.9.1              PSGallery  Pester provides a framework for running BDD style Tests to execute and validate P…

Name   Version Prerelease Repository Description
----   ------- ---------- ---------- -----------
Pester 5.9.1              PSGallery  Pester provides a framework for running BDD style Tests to execute and validate P…

Goal: Get the tools Lessons 4–8 need — Pester and PSScriptAnalyzer — without installing anything for your user. Environment: pwsh 7.6 with Internet access. Cost: about 3 MB in ~/pslab/modules.

Explore versions: Find-PSResource Pester -Version '[5.0,]' and Find-PSResource PSScriptAnalyzer. Write down the newest 5.x and 6.x of Pester.
Save exact versions with metadata:
Save-PSResource -Name Pester -Version 6.2.0 -Path ~/pslab/modules -TrustRepository -IncludeXml
Save-PSResource -Name PSScriptAnalyzer -Version 1.24.0 -Path ~/pslab/modules -TrustRepository -IncludeXml -PassThru |
    Format-Table Name, Version, Repository
Get-InstalledPSResource -Path ~/pslab/modules | Format-Table Name, Version, Repository
Name             Version Repository
----             ------- ----------
PSScriptAnalyzer 1.24.0  PSGallery

Name             Version Repository
----             ------- ----------
Pester           6.2.0   PSGallery
PSScriptAnalyzer 1.24.0  PSGallery
Use them in this session only, then rerun Module 1's script:
$env:PSModulePath = (Join-Path $HOME 'pslab' 'modules') + [IO.Path]::PathSeparator + $env:PSModulePath
Import-Module Pester -RequiredVersion 6.2.0
~/pslab/scripts/needs-pester.ps1
Pester 6.2.0 is loaded
Make a tiny offline mirror: Save-PSResource -Name Pester -Version 5.9.1 -AsNupkg -Path ~/pslab/tmp/mirror -TrustRepository → Pester.5.9.1.nupkg (328,088 bytes on the lab machine). Module 5 turns such a folder into a repository.
Cleanup: keep ~/pslab/modules (Lesson 8 uses it); delete the mirror: Remove-Item ~/pslab/tmp/mirror -Recurse.

Case 1: a “version range” that silently downgraded a linter

Problem: A build script saved PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' to “get the latest 1.x”; new rules never showed up. Root cause: on PSResourceGet 1.2.1 that range resolved to 1.22.0 (reproduced above). Fix: pin an exact version in a required-resource file and update it deliberately; log -PassThru output in CI.

Case 2: a scheduled job that never installs anything

Problem: A bootstrap task ran Install-PSResource Az.Accounts under Task Scheduler and failed every night. Root cause: PSGallery is untrusted → prompt → -NonInteractive error. Fix: install from your own trusted feed (Module 5), or save the exact versions into the image at build time; do not add -TrustRepository for the public gallery on production hosts.

Case 3: two Pester versions on the build agent

Problem: Update-PSResource was expected to fix a bug in an older module version, but the agent still used the old one. Root cause: updates install side by side; a script imported with -RequiredVersion of the old one. Fix: update the pin, not just the machine.

Common errors and fixes

Package 'X' could not be found in any registered repositories.

Cause: wrong name, no version in the range, prerelease without -Prerelease, or the repository is not registered / not reachable.

Find-PSResource X -Version '*' -Prerelease | Select-Object -First 5
Get-PSResourceRepository
PowerShell is in NonInteractive mode. Read and Prompt functionality is not available. (during install/save)

Cause: untrusted repository prompt (or a license prompt) in a non-interactive host. Fix: a trusted internal feed, -TrustRepository deliberately, -AcceptLicense where a license must be accepted.

Installed, but Import-Module still loads the old version

PSModulePath order and version folders (Module 1). Get-Module X -ListAvailable | Format-Table Version, ModuleBase; start a new session.

Administrator rights are required to install … into AllUsers

Use the default CurrentUser scope, or run elevated deliberately for machine-wide installs (images, servers).

Command-line exercises
1. Find the newest Pester 5.x and save exactly that version to ~/pslab/modules.
$v = (Find-PSResource Pester -Version '[5.0,6.0)' | Sort-Object Version -Descending | Select-Object -First 1).Version
Save-PSResource Pester -Version "$v" -Path ~/pslab/modules -TrustRepository -IncludeXml
2. Show which repository would be searched first.
Get-PSResourceRepository | Sort-Object Priority, Name | Select-Object -First 1
Scenario analysis
Your security team asks: “Why can't servers just run Install-PSResource -TrustRepository from the PowerShell Gallery?” Give three reasons and an alternative.

① Anyone can publish to the Gallery; a typo-squatted or compromised package runs with the server's privileges. ② Availability is not guaranteed for production workloads. ③ Without pins, two servers can get different versions on different days. Alternative: promote reviewed exact versions into an internal feed (Azure Artifacts, file share), register only that feed as trusted on servers, and install from required-resource files.

Verified teaching videos

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
English · title and channel verified; shows the older PowerShellGet v2 workflow (Install-Module)

No verified video on PSResourceGet 1.2 was found (searches on 2026-11-24 returned only articles); use the documentation below.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: Install-Module (old logo) and Install-PSResource side by side.
Narration: PowerShell 7.6 ships both; new work uses PSResourceGet.
Shot 2 · 20–50s
Visual: a number line with brackets [5.0, 6.0) highlighting 5.x; then “5.7” highlights one point.
Narration: brackets make ranges; a bare number is exact.
Shot 3 · 50–70s
Visual: a gate “untrusted” stops a CI robot.
Narration: untrusted repositories prompt — and prompts fail in automation.
Shot 4 · 70–90s
Visual: Save-PSResource drops version folders into ~/pslab/modules.
Narration: save exact versions into a folder you control.
or score ≥ 70% on the Quiz

Module 5 · Repositories and publishing: local and private feeds, reproducible installs

28:00 – 35:00 · A repository is a NuGet feed — a folder of .nupkg files or a server. Publishing turns your module folder into a package; pinned, file-driven installs make every machine get the same bits
7 min~/pslab/repo★★★★☆
Learning objectives
  • Explain what a .nupkg contains (your files + .nuspec generated from the manifest) and build one with Compress-PSResource.
  • Register a folder repository with Register-PSResourceRepository -Uri, publish with Publish-PSResource, find and install a pinned version, and undo all of it.
  • Make installs reproducible with Install-PSResource -RequiredResourceFile (.psd1 or .json).
  • Know how private feeds differ: Azure Artifacts and GitHub Packages (NuGet v3, credentials, search limitations), JFrog, ACR, file shares.
Prerequisites: Modules 3–4. Importance:★★★★☆

What: package, feed, repository registration

TermWhat it isOpsKit
Package (.nupkg)A zip: your module files + OpsKit.nuspec (id, version, authors, tags, dependencies taken from the manifest) + NuGet bookkeeping (_rels/, [Content_Types].xml, package/…psmdcp)OpsKit.0.2.0.nupkg, about 6.3 KB
FeedWhere packages live: a folder / SMB share (all PSResourceGet features), a NuGet v2 server, or a NuGet v3 service~/pslab/repo
Repository registrationA name + URI + trust + priority in your PSResourceRepository.xmlPSLabLocal (optional step)

Why: a private feed between the Gallery and your servers

Microsoft's guidance for PSResourceGet is explicit: treat the PowerShell Gallery as untrusted, community-owned and unsuitable as a direct production dependency; use it for discovery and promote reviewed packages into a trusted feed. Your own modules need a home anyway. A feed gives you: immutable versions, one place to install from, and access control.

FeedURI shapeAuth for installNotes (PSResourceGet docs)
Folder / file shareC:\repo, \\server\psrepo, /mnt/psrepoFile-system permissions only (no -Credential)Supports all search scenarios
Azure Artifactshttps://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed>/nuget/v3/index.jsonPrivate feeds need a PAT or the Azure Artifacts Credential Provider (1.2+)No wildcard/tag/command search; publish needs -ApiKey (any string) + -Credential (PAT)
GitHub Packageshttps://nuget.pkg.github.com/<owner>/index.jsonAlways (PAT)Owner = user or org, not a repository; no wildcard/tag search
JFrog Artifactory, MyGet, NuGet.Server, ACRNuGet v3 / …/nuget / https://<registry>.azurecr.ioVariesACR support since 1.1

How: publish, then install a pinned version

  1. Publish-PSResource -Path ~/pslab/out/OpsKit -Repository PSLabLocal validates the manifest, packs the folder (the whole folder — stage it first) and copies the .nupkg to the feed. Compress-PSResource does only the packing, into any folder — handy when you can't or don't want to register a repository.
  2. Install-PSResource OpsKit -Version 0.2.0 -Repository PSLabLocal installs exactly that version; RequiredModules from the manifest become NuGet dependencies and are installed too (not for NuGet v3 feeds in 1.2 — install those yourself).
  3. A required-resource file lists name → version range → repository for a whole environment; Install-PSResource -RequiredResourceFile applies it.

When: which publishing path

SituationUse
Laptop, lab, build artifactCompress-PSResource → .nupkg in a folder
Team on Windows with a shareFolder repository on SMB + Publish-PSResource
Org with CI/CDAzure Artifacts / GitHub Packages; publish from the pipeline with a secret, never from a laptop
Open sourcePowerShell Gallery with an API key (Lesson 8)
Common misconceptions① “Publish only packs the module files” — it packs the folder: notes, tests, .git and secrets included; stage a clean copy. ② “I can re-publish 0.2.0 with a fix” — feeds treat versions as immutable (and caches keep the old bits); bump to 0.2.1. ③ “Registering a repository is per machine” — it's per user (PSResourceRepository.xml under your local app data); a service account has its own list. ④ “-Credential works for a file share” — file-share feeds use the caller's file-system access only. ⑤ “A required-resource file with ranges is reproducible” — only exact versions are.

Architecture diagram: from module folder to another machine

~/pslab/out/OpsKitpsd1 · psm1Public/ · Private/(staged copy) pack OpsKit.0.2.0.nupkgfiles + OpsKit.nuspecid · version · tagsdeps = RequiredModules publish Feed~/pslab/repo (folder)\\share · Azure ArtifactsGitHub Packages install Target machineModules\OpsKit\0.2.0\Import-Module OpsKit-RequiredVersion 0.2.0 Who knows what Your user: PSResourceRepository.xml → Name PSLabLocal · Uri file:///…/pslab/repo · Trusted · Priority The feed: only .nupkg files (immutable versions) The target: requirements.psd1 → OpsKit = @{ version = '[0.2.0]'; repository = 'PSLabLocal' } Secrets (PAT, API key) live in SecretManagement or the CI secret store — never in these files
Figure 5-1: stage → pack → feed → pinned install. Each arrow is a command you can run (or verify) separately

Publish → feed → install → import

Ready.
Real mechanism behind the animation For a local folder feed, PSResourceGet reads *.nupkg file names and the .nuspec inside them; there is no server and no index. Publishing creates the nuspec from the manifest in a temporary folder, zips it with your files, and copies the result to the feed. Installing unzips into <scope>/Name/Version/, removes the NuGet bookkeeping files and writes PSGetModuleInfo.xml.

Command table

CommandPurposeNotes
Compress-PSResource -Path dir -DestinationPath feedBuild Name.Version.nupkgNo repository needed; -PassThru returns the file
Register-PSResourceRepository -Name N -Uri path -TrustedAdd a feed to your listChanges user state; undo: Unregister-PSResourceRepository N
Publish-PSResource -Path dir -Repository NPack and push-ApiKey/-Credential for servers; -NupkgPath to push an existing package
Find-PSResource -Repository NSearch one feedFolder feeds support wildcards
Install-PSResource X -Version 0.2.0 -Repository NPinned install-Version '[0.2.0]' is the same in range syntax
Install-PSResource -RequiredResourceFile f.psd1Install a whole set.psd1 or .json; also -RequiredResource @{…}
Save-PSResource X -AsNupkg -Path dirMirror packages into a folder feedPromotion from Gallery to internal feed
# Pack OpsKit into the folder feed — no registration, nothing changes outside ~/pslab
Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/repo -PassThru
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          11/24/2026  9:06 PM           6328 OpsKit.0.2.0.nupkg
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [IO.Compression.ZipFile]::OpenRead((Join-Path $HOME 'pslab' 'repo' 'OpsKit.0.2.0.nupkg'))
$zip.Entries | Sort-Object FullName | Format-Table FullName, Length
$r = [IO.StreamReader]::new(($zip.Entries | Where-Object FullName -eq 'OpsKit.nuspec').Open()); $r.ReadToEnd(); $r.Dispose(); $zip.Dispose()
FullName                                                                          Length
--------                                                                          ------
_rels/.rels                                                                          500
[Content_Types].xml                                                                  593
OpsKit.nuspec                                                                        732
OpsKit.psd1                                                                         4430
OpsKit.psm1                                                                          866
package/services/metadata/core-properties/5eb4b66b64f74175bf905fdb75a7e0e3.psmdcp    761
Private/ConvertTo-OpsServer.ps1                                                      523
Private/Resolve-OpsPath.ps1                                                          264
Public/Get-OpsConfig.ps1                                                             649
Public/Get-OpsServer.ps1                                                             626
Public/Test-OpsEndpoint.ps1                                                          812

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <id>OpsKit</id>
    <version>0.2.0</version>
    <authors>PowerShell course</authors>
    <owners>pslab</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <projectUrl>https://example.com/pslab/opskit</projectUrl>
    <description>OpsKit: inventory, configuration and endpoint checks for the PowerShell course.</description>
    <releaseNotes>0.2.0: packaged as a script module with a manifest.</releaseNotes>
    <copyright>(c) PowerShell course. All rights reserved.</copyright>
    <tags>PSModule Operations Inventory Course</tags>
  </metadata>
</package>

How to verify: every value in the nuspec came from OpsKit.psd1; the PSModule tag was added automatically (galleries use it to filter modules from scripts). Everything in the source folder was packed — had notes.txt or a tests/ folder been there, they would be inside too. Common mistake: packing the working folder. Production use: pack a staged copy (Module 8) in CI.

Optional: a registered folder repository (changes your repository list)

Register-PSResourceRepository -Name PSLabLocal -Uri (Convert-Path ~/pslab/repo) -Trusted -PassThru
Publish-PSResource -Path ~/pslab/out/OpsKit -Repository PSLabLocal        # Module 8 builds ~/pslab/out/OpsKit
Find-PSResource -Name OpsKit -Repository PSLabLocal
Install-PSResource -Name OpsKit -Version 0.2.0 -Repository PSLabLocal -PassThru
Get-InstalledPSResource -Name OpsKit | Format-Table Name, Version, Repository, InstalledLocation
Name       Uri                                 Trusted Priority IsAllowedByPolicy
----       ---                                 ------- -------- -----------------
PSLabLocal file:///C:/Users/labadmin/pslab/repo True    50       True

Name   Version Prerelease Repository Description
----   ------- ---------- ---------- -----------
OpsKit 0.2.0              PSLabLocal OpsKit: inventory, configuration and endpoint checks for the PowerShell course.

Name   Version Prerelease Repository Description
----   ------- ---------- ---------- -----------
OpsKit 0.2.0              PSLabLocal OpsKit: inventory, configuration and endpoint checks for the PowerShell course.

Name   Version Repository InstalledLocation
----   ------- ---------- -----------------
OpsKit 0.2.0   PSLabLocal C:\Users\labadmin\Documents\PowerShell\Modules
# Undo
Uninstall-PSResource -Name OpsKit -Version 0.2.0
Unregister-PSResourceRepository -Name PSLabLocal

Why “Expected”: PSResourceGet 1.2.1 keeps the repository list in a fixed per-user file (%LOCALAPPDATA%\PSResourceGet\PSResourceRepository.xml on Windows — it ignored a redirected LOCALAPPDATA in a child process during verification), so these commands cannot be isolated to a lab folder. Module 8 and the integrated lab verify the same package by unpacking it exactly where an install would and importing it by version.

Reproducible installs

# ~/pslab/requirements.psd1
@{
    'OpsKit'           = @{ version = '[0.2.0]';  repository = 'PSLabLocal' }
    'Pester'           = @{ version = '[6.2.0]';  repository = 'PSGallery' }
    'PSScriptAnalyzer' = @{ version = '[1.24.0]'; repository = 'PSGallery' }
}
Import-PowerShellDataFile ~/pslab/requirements.psd1 | ForEach-Object GetEnumerator |
    Sort-Object Key | Format-Table Key, @{ n = 'Version'; e = { $_.Value.version } }, @{ n = 'Repository'; e = { $_.Value.repository } }
# Optional (installs into CurrentUser):
Install-PSResource -RequiredResourceFile ~/pslab/requirements.psd1 -TrustRepository
Key              Version  Repository
---              -------  ----------
OpsKit           [0.2.0]  PSLabLocal
Pester           [6.2.0]  PSGallery
PSScriptAnalyzer [1.24.0] PSGallery

The same content as JSON (requirements.json) works with the same parameter. '[0.2.0]' is NuGet for “exactly 0.2.0”. Commit the file next to the code that needs it.

Private feeds (overview)

# Azure Artifacts (NuGet v3). Install from a private feed needs a PAT or the Azure Artifacts Credential Provider.
Register-PSResourceRepository -Name CorpFeed -Uri 'https://pkgs.dev.azure.com/MyOrg/MyProject/_packaging/MyFeed/nuget/v3/index.json' -Trusted
$cred = Get-Secret -Name AdoPackagingPat        # SecretManagement (Lesson 7) — never a literal token
Publish-PSResource -Path ./out/OpsKit -Repository CorpFeed -ApiKey 'AzureDevOps' -Credential $cred

# GitHub Packages (NuGet v3, credentials for every operation; owner = user or organisation)
Register-PSResourceRepository -Name GitHubFeed -Uri 'https://nuget.pkg.github.com/MyGitHubOrg/index.json'

Goal: Produce OpsKit.0.2.0.nupkg in your folder feed and understand exactly what is inside. Environment: OpsKit with manifest (Module 3). Cost: none. Registration and install are optional.

Pack: Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/repo -PassThru.
Inspect the package entries and the nuspec with the ZipFile commands from the Commands tab. Which manifest keys appear in the nuspec?
See the danger: create ~/pslab/OpsKit/notes.txt with the text TODO: password = hunter2, pack into ~/pslab/tmp, and list the entries:
Set-Content ~/pslab/OpsKit/notes.txt -Value 'TODO: password = hunter2'
$pkg = Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/tmp -PassThru
Add-Type -AssemblyName System.IO.Compression.FileSystem
$z = [IO.Compression.ZipFile]::OpenRead($pkg.FullName); $z.Entries.FullName | Where-Object { $_ -notmatch '^(_rels|package)/|Content_Types' }; $z.Dispose()
Remove-Item ~/pslab/OpsKit/notes.txt, $pkg.FullName
OpsKit.nuspec
notes.txt
OpsKit.psd1
OpsKit.psm1
Private/ConvertTo-OpsServer.ps1
Private/Resolve-OpsPath.ps1
Public/Get-OpsConfig.ps1
Public/Get-OpsServer.ps1
Public/Test-OpsEndpoint.ps1
Module 8 stages a clean copy so this cannot happen.
Write the required-resource file ~/pslab/requirements.psd1 and check it with Import-PowerShellDataFile.
Optional (changes your user state): register PSLabLocal, find and install OpsKit 0.2.0, import it, then uninstall and unregister.
Cleanup: keep ~/pslab/repo for now — Module 8 rebuilds the package with its own script (delete ~/pslab/repo/OpsKit.0.2.0.nupkg first, or the script will refuse to overwrite the release).

Case 1: a secret in a published package

Problem: A module on an internal feed contained dev.settings.json with a service principal secret. Root cause: Publish-PSResource -Path . from the repository root packed everything. Fix: rotate the secret; stage only manifest-listed files (or use FileList as documentation and a build that copies just those); scan packages in CI. Feeds keep old versions — deleting the package is not enough.

Case 2: “same version, different code”

Problem: Two servers installed OpsKit 1.4.0 a week apart and behaved differently. Root cause: someone deleted and re-published 1.4.0 on the file-share feed. Fix: make the feed append-only (permissions), bump versions for every change, and fail the build if the version already exists (Module 8's script does).

Case 3: pipeline can't install from the private feed

Problem: Install-PSResource worked on laptops but failed in CI against Azure Artifacts. Root cause: laptops had cached credentials; the agent had none. Fix: pass a PAT from the pipeline secret store via -Credential or configure the Azure Artifacts Credential Provider (supported since PSResourceGet 1.2), and register the repository in the job, not on the image.

Common errors and fixes

Publish/Install says the repository does not exist
Get-PSResourceRepository

Registration is per user: a service account, a container or a CI job must register the feed itself.

Package already exists / version conflict on publish

Bump ModuleVersion. Do not delete and re-publish a released version.

Unauthorized (401/403) from Azure Artifacts or GitHub Packages

Missing or expired PAT, wrong scope (Packaging read/write for Azure Artifacts), or a GitHub feed URL with a repository name instead of the owner.

Dependencies are not installed from a NuGet v3 feed

PSResourceGet 1.2 does not install dependencies from v3 feeds; list them explicitly in your required-resource file.

Command-line exercises
1. List the files inside any .nupkg without extracting it.
Add-Type -AssemblyName System.IO.Compression.FileSystem
$z = [IO.Compression.ZipFile]::OpenRead((Convert-Path ~/pslab/repo/OpsKit.0.2.0.nupkg)); $z.Entries.FullName; $z.Dispose()
2. Mirror exactly Pester 6.2.0 from the Gallery into your folder feed for offline servers.
Save-PSResource -Name Pester -Version 6.2.0 -AsNupkg -Path ~/pslab/repo -TrustRepository
Scenario analysis
Design the module supply chain for 300 Windows servers that may not reach the Internet.

An internal Azure Artifacts (or SMB) feed is the only registered, trusted repository on servers. A promotion pipeline saves reviewed Gallery packages with Save-PSResource -AsNupkg, scans them, and pushes them. Your own modules are published by CI from staged builds with immutable versions. Servers apply a required-resource file with exact versions; drift is detected with Get-InstalledPSResource. Credentials come from a secret store, never from scripts.

Verified teaching videos

▶
PowerShell Master Class - Automation — John Savill's Technical Training
English · automation context for shipping modules (title and channel verified)
▶
New PowerShell Secrets Management Module - Easily use any secret provider — John Savill's Technical Training
English · where feed credentials should live (title and channel verified)

No verified video covers PSResourceGet folder repositories or Compress-PSResource.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a module folder is zipped into a box stamped “OpsKit 0.2.0”, a nuspec label printed from the psd1.
Narration: a package is your folder plus a label generated from the manifest.
Shot 2 · 25–50s
Visual: boxes on a shelf (feed); one box tries to replace another with the same stamp and is rejected.
Narration: feeds are shelves of immutable versions.
Shot 3 · 50–75s
Visual: a requirements.psd1 checklist drives three servers to the same versions.
Narration: pinned files make installs reproducible.
Shot 4 · 75–90s
Visual: Gallery → review gate → internal feed → servers.
Narration: promote, don't pull straight from the internet.
or score ≥ 70% on the Quiz

Module 6 · Providers and drives: FileSystem, Env, Registry, Cert, Variable, Function

35:00 – 42:00 · A provider makes a data store look like a file system. The same Get-ChildItem, Get-Item, New-Item and Get-ItemProperty work on files, environment variables, functions, certificates and the registry — with provider-specific rules
7 minGet-PSProvider · New-PSDrive★★★☆☆
Learning objectives
  • List providers and drives with Get-PSProvider / Get-PSDrive, and read the capabilities that explain why -Filter works on files but not on Env:.
  • Use Env:, Variable:, Function: and Alias: with item cmdlets; read Cert: and HKLM:/HKCU: (Windows) read-only; distinguish items (keys) from item properties (registry values).
  • Create a session drive with New-PSDrive to ~/pslab/data, and know why .NET methods cannot see PowerShell drives (Convert-Path).
Prerequisites: Lesson 1 Module 5 (PSPath). Importance:★★★☆☆

What: providers and drives

ProviderDrivesItems areItem propertiesPlatform
FileSystemC:, /, Temp:files, foldersattributes, times (rarely used)all
EnvironmentEnv:environment variables of this process—all
VariableVariable:PowerShell variables—all
FunctionFunction:functions and filters (including module exports)—all
AliasAlias:aliases—all
CertificateCert:stores and X.509 certificates—Windows
RegistryHKLM:, HKCU:keysvalues (name/data pairs)Windows

A drive is a named root inside one provider. New-PSDrive adds your own: a short name for a deep folder, a registry branch, or a network share. Drives exist only in the current session (unless -Persist creates a real Windows mapped drive).

Why: one set of verbs for every store

CmdletFilesEnv:Registry
Get-ChildItemlist folderlist variableslist subkeys
Get-Item / Test-Pathone fileone variableone key
New-Item, Remove-Item, Rename-Item, Copy-Item✓✓ (process only)✓ (keys)
Get-Content / Set-Contentfile textvalue—
Get-ItemProperty, Get-ItemPropertyValue, Set-ItemProperty, New-ItemPropertyrare—values

How: provider paths and capabilities

  • Every item carries a PSPath: Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv. That provider-qualified form works anywhere, even for paths without a drive.
  • Capabilities say what the provider supports: FileSystem has Filter (fast native filtering) and Credentials; the others only ShouldProcess. -Filter on Env: fails; use Where-Object or a wildcard path (Env:\PS*).
  • .NET methods ([IO.File]::ReadAllText) know nothing about PowerShell drives: pass (Convert-Path Lab:\servers.csv) — Module 7 shows the same problem with ~.

When: what the course uses

OpsKit reads files (FileSystem) and configuration (a data file); Lesson 7 reads secrets and environment variables (Env:); Lesson 8 checks code-signing certificates (Cert:\CurrentUser\My -CodeSigningCert). The registry appears in Windows inventory scripts — read it freely, write it only through change management.

Common misconceptions① “Registry values are items” — values are item properties of a key; Get-ChildItem lists subkeys, not values. ② “$env:X = 1 sets it permanently” — only for this process and its children; persistent variables need [Environment]::SetEnvironmentVariable(…, 'User') on Windows or your shell profile on Linux. ③ “New-PSDrive drives are visible in Explorer” — not without -Persist, and never to other processes. ④ “Get-ChildItem Env: -Filter PS* works” — verified error: the provider does not support filters. ⑤ “Cert: and HKLM: exist everywhere” — Windows only.

Architecture diagram: one cmdlet, many providers

Get-ChildItem / Get-Item / New-Itempath → drive → provider FileSystemC: · Lab:Filter ✓ EnvironmentEnv:process only VariableVariable:$x ⇔ Variable:\x FunctionFunction:OpsKit exports AliasAlias:gci → Get-ChildItem CertificateCert:Windows RegistryHKLM: · HKCU:keys + values PSPath = Provider::provider-path, e.g. Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv .NET APIs see only provider paths → Convert-Path Lab:\servers.csv before calling [IO.File]::… Registry: key = item (Get-ChildItem) · value = item property (Get-ItemProperty / Get-ItemPropertyValue)
Figure 6-1: the verbs are shared; capabilities and item shapes differ per provider

Path → provider → item

Ready.

Command table

CommandPurposeNotes
Get-PSProviderProviders, capabilities, drivesCertificate appears after its module loads
Get-PSDrive [-PSProvider X]DrivesFileSystem drives show free space
New-PSDrive -Name Lab -PSProvider FileSystem -Root ~/pslab/dataSession driveRemove-PSDrive Lab
Get-ItemProperty Key -Name V / Get-ItemPropertyValue Key -Name VRegistry valuesThe second returns the bare value
Convert-Path X, Resolve-Path XPowerShell path → provider pathFor .NET and native tools
Test-Path Env:\X, Test-Path Function:\Get-OpsServerExistence checks in any provider
Get-PSProvider | Format-Table Name, Capabilities, @{ n = 'Drives'; e = { $_.Drives.Name -join ', ' } } -AutoSize
Name                              Capabilities Drives
----                              ------------ ------
Registry                         ShouldProcess HKLM, HKCU
Alias                            ShouldProcess Alias
Environment                      ShouldProcess Env
FileSystem  Filter, ShouldProcess, Credentials C, D, G, Temp, N
Function                         ShouldProcess Function
Variable                         ShouldProcess Variable
$env:OPSKIT_ENV = 'staging'
Get-ChildItem Env:\OPSKIT* | Format-Table Name, Value
Remove-Item Env:\OPSKIT_ENV; Test-Path Env:\OPSKIT_ENV
Import-Module ~/pslab/OpsKit
(Get-ChildItem Function:\*-Ops*).Name
New-Item Alias:\gos -Value Get-OpsServer | Format-Table Name, Definition
(gos -Environment staging).Count
Get-ChildItem Env: -Filter 'PS*'
Name       Value
----       -----
OPSKIT_ENV staging

False
Get-OpsConfig
Get-OpsServer
Test-OpsEndpoint

Name Definition
---- ----------
gos  Get-OpsServer

3
Get-ChildItem: Cannot call method. The provider does not support the use of filters.

How to verify: module exports really are items in Function:; an alias created with New-Item works like Set-Alias. Common mistake: -Filter outside the file system — use Get-ChildItem Env:\PS* or Where-Object Name -like 'PS*'.

# Read-only: certificates and registry (Windows)
Get-ChildItem Cert:\ | Format-Table Location
Get-ChildItem Cert:\LocalMachine\Root | Where-Object Subject -like '*Microsoft Root Certificate Authority 2011*' |
    Format-List Subject, NotAfter, HasPrivateKey
@(Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert).Count
Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ProductName, CurrentBuild, DisplayVersion |
    Format-List ProductName, CurrentBuild, DisplayVersion
Get-ItemPropertyValue 'HKCU:\Control Panel\International' -Name sShortDate
(Get-Item 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').GetType().FullName
    Location
    --------
 CurrentUser
LocalMachine

Subject       : CN=Microsoft Root Certificate Authority 2011, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
NotAfter      : 3/22/2036 6:13:04 PM
HasPrivateKey : False

0

ProductName    : Windows 10 Pro
CurrentBuild   : 26300
DisplayVersion : 26H2

M/d/yyyy
Microsoft.Win32.RegistryKey

Yes, ProductName says “Windows 10 Pro” on Windows 11 — a long-standing registry quirk; use CurrentBuild (≥ 22000 means Windows 11) or Get-CimInstance Win32_OperatingSystem. A registry key is a Microsoft.Win32.RegistryKey object; its values are properties.

New-PSDrive -Name Lab -PSProvider FileSystem -Root ~/pslab/data | Format-Table Name, Provider
Get-ChildItem Lab:\ -File | Format-Table Name, Length
Get-Content Lab:\servers.csv -TotalCount 2
(Get-Item Lab:\servers.csv).PSPath
Convert-Path Lab:\servers.csv
Remove-PSDrive Lab
Name Provider
---- --------
Lab  Microsoft.PowerShell.Core\FileSystem

Name               Length
----               ------
access.log          80646
inventory.json       1599
opskit.config.psd1    777
servers.csv           600

Name,Env,Region,IP,Role,Monitored
web-01,dev,canadacentral,10.10.1.21,web,true
Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv
C:\Users\labadmin\pslab\data\servers.csv
# Same item verbs across providers
New-Item -Path Variable:\ -Name OpsLevel -Value 'Information' | Format-Table Name, Value
Set-Item -Path Variable:\OpsLevel -Value 'Verbose'; $OpsLevel
Copy-Item Variable:\OpsLevel Variable:\OpsLevelBackup; $OpsLevelBackup
Remove-Item Variable:\OpsLevel, Variable:\OpsLevelBackup
Name     Value
----     -----
OpsLevel Information

Verbose
Verbose

Goal: Navigate five providers with the same verbs, and give OpsKit's data folder a drive. Environment: pwsh 7.6 (Cert/Registry steps on Windows only). Safety: registry and certificate steps are read-only; environment changes affect only this process. Cost: none.

Survey: Get-PSProvider; Get-PSDrive -PSProvider Environment, Variable, Function, Alias.
Env for one process: set $env:OPSKIT_ENV = 'prod', then prove a child sees it and the parent of your shell does not: pwsh -NoProfile -Command '$env:OPSKIT_ENV'. Remove it with Remove-Item Env:\OPSKIT_ENV.
A Lab: drive: create it, list it, read servers.csv through it, then try [IO.File]::ReadAllLines('Lab:\servers.csv') and fix it with Convert-Path.
Windows only, read-only: list Cert:\CurrentUser\My (count only), read CurrentBuild from HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion with Get-ItemPropertyValue, and list the subkeys of HKCU:\Software\Microsoft (names only, -Name).
Cleanup: Remove-PSDrive Lab -ErrorAction Ignore; nothing else was written.

Case 1: a “registry read” that read nothing

Problem: An inventory script used Get-ChildItem HKLM:\…\Uninstall\App to read DisplayVersion and got empty results. Root cause: values are item properties; Get-ChildItem returns subkeys. Fix: Get-ItemPropertyValue -Path … -Name DisplayVersion; and on 64-bit Windows also check HKLM:\SOFTWARE\WOW6432Node\… for 32-bit apps.

Case 2: the environment variable that vanished

Problem: A setup script set $env:OPSKIT_CONFIG; the scheduled job that ran later did not see it. Root cause: Env: changes are process-local. Fix: pass configuration as parameters (Lesson 1, Module 1 principle), or set a machine/user variable deliberately through configuration management.

Case 3: a drive that only worked interactively

Problem: Scripts used Lab:\… created in a profile; under Task Scheduler they failed with “Cannot find drive”. Root cause: drives are session state; profiles do not load with -NoProfile. Fix: build paths from parameters and Join-Path; create drives inside the script if you want them.

Common errors and fixes

Cannot call method. The provider does not support the use of filters.

-Filter is a FileSystem capability. Use a wildcard in the path or Where-Object.

Cannot find drive. A drive with the name 'Lab' does not exist.

New session, job, or another runspace. Create the drive there, or use real paths.

Requested registry access is not allowed / Access denied (HKLM)

Writing HKLM needs elevation; reading some keys too. This lesson reads only.

Exception calling ".NET method" … Could not find a part of the path 'C:\…\Lab:\…'

.NET does not understand PowerShell drives or ~: Convert-Path first.

Command-line exercises
1. Show all environment variables whose name starts with PS, sorted.
Get-ChildItem Env:\PS* | Sort-Object Name | Format-Table Name, Value
2. Read the Windows build number as an integer (Windows only).
[int](Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name CurrentBuild)
Scenario analysis
A teammate wants OpsKit to store its default environment in the registry “because that's where Windows stores settings”. Respond.

It would make OpsKit Windows-only (no HKCU: on Linux/macOS), invisible in source control and hard to test. Keep configuration in opskit.config.psd1 (portable, reviewable, read safely as data) and let parameters override it. Use the registry only for reading Windows facts.

Verified teaching videos

▶
PowerShell Master Class - Data and Objects — John Savill's Technical Training
English · objects and data sources such as the registry (title and channel verified)
▶
PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson
English · beginner course (title and channel verified)

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: seven drawers labelled C:, Env:, Variable:, Function:, Alias:, Cert:, HKLM:, one cmdlet opens each.
Narration: providers make every store look like a drive.
Shot 2 · 25–55s
Visual: a registry key opens to show values as cards attached to it.
Narration: keys are items, values are item properties.
Shot 3 · 55–75s
Visual: a Lab: shortcut points to ~/pslab/data; a .NET robot can't read the sign until Convert-Path translates it.
Narration: drives are PowerShell-only; convert paths for .NET.
Shot 4 · 75–90s
Visual: -Filter bounces off Env:.
Narration: capabilities differ — Filter is for files.
or score ≥ 70% on the Quiz

Module 7 · Cross-platform: paths, case, encodings, line endings and environment variables

42:00 – 50:00 · The same .ps1 runs on Windows, Linux and macOS only if it never hard-codes separators, never assumes case-insensitive files, writes encodings deliberately and splits text and paths portably
8 minJoin-Path · Format-Hex★★★★☆
Learning objectives
  • Build paths with Join-Path, Split-Path (-Leaf, -LeafBase, -Extension) and [IO.Path], and know where ~ and relative paths break .NET calls.
  • Branch on $IsWindows/$IsLinux/$IsMacOS and avoid Windows-only cmdlets or guard them.
  • Prove encodings with Format-Hex: pwsh 7 writes UTF-8 without BOM; Windows PowerShell 5.1's > writes UTF-16 LE and Set-Content writes the ANSI code page.
  • Handle CRLF vs LF when splitting text, and split $env:PATH with [IO.Path]::PathSeparator.
Prerequisites: Modules 1 and 6. Importance:★★★★☆

What: the differences that matter

TopicWindowsLinux / macOSPortable code
Directory separator\ (also accepts /)/ onlyJoin-Path; / in literals works on both
Path list separator (PATH, PSModulePath);:[IO.Path]::PathSeparator
File-name caseinsensitive (NTFS default)sensitive (Linux), insensitive by default (macOS APFS)Use the exact case everywhere
Env var namesinsensitive ($env:path = $env:PATH)sensitiveExact case
Line ending written by Set-ContentCRLFLFSplit on '\r?\n'; write with explicit "`n" when it matters
Default encoding (pwsh 7)UTF-8 without BOM for all cmdlets and >-Encoding when a consumer needs something else
Hidden filesattributeleading dot-Force
Aliases like ls, cat, sortPowerShell aliasesnative toolsFull cmdlet names (Lesson 1)

Why: encodings — what Windows PowerShell 5.1 did

Writerpwsh 7.6Windows PowerShell 5.1
Set-Content, Add-ContentUTF-8, no BOM“Default” = the system ANSI code page (1252 on most Western systems; UTF-8 on the lab machine, whose “Unicode UTF-8 for worldwide language support” option sets ACP 65001)
>, Out-FileUTF-8, no BOMUTF-16 LE with BOM (FF FE)
-Encoding UTF8UTF-8 no BOM (utf8BOM for a BOM)UTF-8 with BOM
Reading a file without BOMas UTF-8as ANSI → café becomes café on a 1252 system

Most problems appear when files cross the boundary: a script saved as UTF-8 without BOM and run by 5.1 (non-ASCII string literals break), a CSV written by 5.1's > that a Linux tool reads as binary, or a BOM that breaks a shebang line or a JSON parser.

How: rules for OpsKit

  • Paths: Join-Path $HOME 'pslab' 'data', $PSScriptRoot, never "$HOME\pslab".
  • Before calling .NET: Convert-Path (resolves ~, drives and relative paths against the PowerShell location; .NET uses the process directory instead — verified below).
  • Text output for other tools: -Encoding utf8NoBOM (the 7.x default, stated explicitly for readers and for 5.1 compatibility checks); BOM only when a Windows consumer requires it.
  • Source files: UTF-8; if a script must run in 5.1 and contains non-ASCII text, save it with BOM.
  • Repository: a .gitattributes such as * text=auto eol=lf plus *.ps1 text eol=crlf only if Windows-only tools need CRLF — decide once.

When: platform checks

if ($IsWindows) { Get-Service -Name W32Time } else { systemctl is-active chronyd }   # $IsWindows is undefined in 5.1 → $null → else branch!

In code that must also run in 5.1, use if ($PSVersionTable.PSEdition -eq 'Desktop' -or $IsWindows). Windows-only commands in 7.6 include the Registry/Certificate providers, Get-Service, Get-CimInstance, Get-WinEvent, Get-Counter and Import-Module -UseWindowsPowerShell (Windows compatibility for 5.1-only modules).

Common misconceptions① “Join-Path resolves ~” — verified: it returns the literal ~\pslab\data\servers.csv; .NET then looks for a folder named ~. ② “UTF-8 is UTF-8” — with or without BOM matters to parsers, and 5.1's -Encoding UTF8 means with BOM. ③ “Get-Content -Raw + -split "`n" gives clean lines” — on CRLF files every line keeps a trailing `r (verified: length 7 for web-01). ④ “If it works on Windows the case is right” — Linux will disagree. ⑤ “$IsWindows exists everywhere” — not in 5.1.

Byte-level view: the same word, five encodings

'café' + newline, written on Windows (bytes from Format-Hex, verified) pwsh 7 Set-Content / > 63 61 66 C3 A9 0D 0A UTF-8, no BOM (é = C3 A9) -Encoding utf8BOM EF BB BF 63 61 66 C3 A9 0D 0A BOM EF BB BF first 5.1 > / Out-File FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00 UTF-16 LE, BOM FF FE Windows-1252 (ANSI) 63 61 66 E9 0D 0A one byte per character LF only ("`n" join) 63 61 66 C3 A9 0A what Linux tools expect
Figure 7-1: identical text, different bytes. Read UTF-8 bytes as 1252 and C3 A9 becomes “é”

Flowchart: making a path portable

"$HOME\pslab\data"breaks on Linux Join-Path $HOME pslab dataright separator Convert-Pathabsolute, ~ resolved .NET / native toolsame file everywhere And keep the case exact: ~/pslab/data/servers.csv ≠ ~/pslab/DATA/Servers.csv on Linux
Figure 7-2: separator, resolution, case — three independent ways a path can be non-portable

One script, Windows vs Linux

Ready.
About the Linux side Windows results were run on 7.6.10. Linux behavior (case-sensitive files, : separator, missing Windows cmdlets) follows the documentation and is labelled as expected; run the lab in a mcr.microsoft.com/powershell container or on a Linux VM to see it yourself.

Command table

CommandPurposeNotes
Join-Path $a b cCombine with the right separatorSeveral child paths (7.x); does not resolve ~
Split-Path $p -Parent | -Leaf | -LeafBase | -ExtensionTake paths apart-LeafBase/-Extension are 7.x
[IO.Path]::Combine(), ::Join().NET combiningCombine restarts at a rooted segment
[IO.Path]::DirectorySeparatorChar, ::PathSeparator\//, ;/:
Convert-PathAbsolute provider pathBefore .NET calls
Format-Hex -Path fShow bytesThe encoding truth
-Encoding utf8NoBOM | utf8BOM | unicode | ascii | 1252Choose encodingCode-page numbers accepted in 7.x
$IsWindows, $IsLinux, $IsMacOS, $PSVersionTable.PlatformPlatform checksUndefined in 5.1
Join-Path ~/pslab data servers.csv
Join-Path -Path 'C:\a' -ChildPath 'b', 'c.txt'
[IO.Path]::Combine('pslab', 'data', 'servers.csv')
[IO.Path]::Combine('pslab', 'C:\data', 'x.csv')
'{0} | {1} | {2}' -f [IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar, [IO.Path]::PathSeparator
$p = '~/pslab/data/opskit.config.psd1'
Split-Path $p -Parent; Split-Path $p -Leaf; Split-Path $p -LeafBase; Split-Path $p -Extension
Test-Path ~/PSLAB/DATA/SERVERS.CSV
Get-Item ~/pslab/data/SERVERS.CSV | Select-Object -ExpandProperty Name
'IsWindows={0} IsLinux={1} IsMacOS={2}' -f $IsWindows, $IsLinux, $IsMacOS
$PSVersionTable.Platform; $PSVersionTable.OS
~\pslab\data\servers.csv
C:\a\b\c.txt
pslab\data\servers.csv
C:\data\x.csv
\ | / | ;
~\pslab\data
opskit.config.psd1
opskit.config
.psd1
True
SERVERS.CSV
IsWindows=True IsLinux=False IsMacOS=False
Win32NT
Microsoft Windows 10.0.26300

How to verify: Windows found SERVERS.CSV — and even reported the name in the case you typed, not the real servers.csv, so case bugs stay invisible on Windows. On Linux Test-Path returns False. Combine threw away pslab because C:\data is rooted.

~/pslab/data/servers.csv
…
/ | / | :
…
False
Get-Item: Cannot find path '/home/labadmin/pslab/data/SERVERS.CSV' because it does not exist.
IsWindows=False IsLinux=True IsMacOS=False
Unix
# ~ and relative paths in .NET calls
[IO.File]::ReadAllText((Join-Path ~/pslab data servers.csv)).Length
[IO.File]::ReadAllText((Convert-Path ~/pslab/data/servers.csv)).Length
[Environment]::CurrentDirectory -eq (Get-Location).Path
Exception calling "ReadAllText" with "1" argument(s): "Could not find a part of the path 'C:\Users\labadmin\AppData\Local\Temp\~\pslab\data\servers.csv'."
600
False

.NET resolved the relative ~\… against the process directory (where pwsh started), not your PowerShell location — two bugs in one line. Convert-Path fixes both.

Set-Location ~/pslab/tmp
function Show-Bytes([string]$Path) { ((Format-Hex -Path $Path).Bytes | ForEach-Object { '{0:X2}' -f $_ }) -join ' ' }
Set-Content -Path enc-default.txt -Value 'café'
'café' > enc-redirect.txt
Set-Content -Path enc-bom.txt   -Value 'café' -Encoding utf8BOM
Set-Content -Path enc-utf16.txt -Value 'café' -Encoding unicode
Set-Content -Path enc-1252.txt  -Value 'café' -Encoding ([Text.Encoding]::GetEncoding(1252))
Set-Content -Path enc-lf.txt    -Value ('café', 'bar' -join "`n") -NoNewline
foreach ($f in 'enc-default.txt', 'enc-redirect.txt', 'enc-bom.txt', 'enc-utf16.txt', 'enc-1252.txt', 'enc-lf.txt') {
    '{0,-17} {1}' -f $f, (Show-Bytes $f)
}
Get-Content enc-default.txt -Encoding 1252      # UTF-8 bytes decoded as ANSI
Get-Content enc-1252.txt                         # ANSI bytes decoded as UTF-8
enc-default.txt   63 61 66 C3 A9 0D 0A
enc-redirect.txt  63 61 66 C3 A9 0D 0A
enc-bom.txt       EF BB BF 63 61 66 C3 A9 0D 0A
enc-utf16.txt     FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00
enc-1252.txt      63 61 66 E9 0D 0A
enc-lf.txt        63 61 66 C3 A9 0A 62 61 72
café
caf�
# The same writes in Windows PowerShell 5.1, bytes checked from pwsh
powershell.exe -NoProfile -Command "Set-Location ~/pslab/tmp; Set-Content ps51-setcontent.txt 'café'; 'café' > ps51-redirect.txt; Out-File ps51-outfile.txt -InputObject 'café'; Set-Content ps51-utf8.txt 'café' -Encoding UTF8"
foreach ($f in 'ps51-setcontent.txt', 'ps51-redirect.txt', 'ps51-outfile.txt', 'ps51-utf8.txt') { '{0,-20} {1}' -f $f, (Show-Bytes $f) }
ps51-setcontent.txt  63 61 66 C3 A9 0D 0A
ps51-redirect.txt    FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00
ps51-outfile.txt     FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00
ps51-utf8.txt        EF BB BF 63 61 66 C3 A9 0D 0A

How to verify: 5.1's > and Out-File wrote UTF-16 LE; -Encoding UTF8 added a BOM. Set-Content wrote the system ANSI code page — UTF-8 here only because this machine's ACP is 65001 ((Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Nls\CodePage).ACP); on a typical 1252 system it writes 63 61 66 E9 0D 0A like enc-1252.txt. Production use: state -Encoding whenever another program reads the file.

# CRLF vs LF when splitting
Set-Content crlf.txt -Value 'web-01', 'api-01'
$raw = Get-Content crlf.txt -Raw
$first = ($raw -split "`n")[0]
$first.Length; $first -eq 'web-01'
($raw -split '\r?\n')[0] -eq 'web-01'
(Get-Content crlf.txt)[0] -eq 'web-01'
($env:PATH -split [IO.Path]::PathSeparator).Count -gt 3; $env:path -eq $env:PATH
7
False
True
True
True
True

Goal: Make OpsKit-style code portable and prove encodings at byte level. Environment: pwsh 7.6; step 3 needs Windows PowerShell 5.1 (Windows); step 5 optionally a Linux container. Cost: none.

Audit OpsKit: Get-ChildItem ~/pslab/OpsKit -Recurse -Include *.ps1, *.psm1 | Select-String -Pattern '\\', ';' -SimpleMatch. On the lab machine it found four lines, none a path: the [\\/] regex in Resolve-OpsPath, two help comments and a hashtable — OpsKit builds every path with Join-Path and resolves ~ in Resolve-OpsPath.
Encodings in pwsh 7: run the Show-Bytes block from the Commands tab in ~/pslab/tmp.
Encodings in 5.1 (Windows): run the powershell.exe line and compare. Check your machine's ANSI code page with the registry line from the explanation — is your ps51-setcontent.txt UTF-8 or 1252?
Line endings: reproduce the `r bug with -split "`n" and fix it with '\r?\n'.
Optional, Linux: docker run --rm -it -v "$HOME/pslab:/root/pslab" mcr.microsoft.com/powershell:lts pwsh, then Test-Path ~/pslab/data/SERVERS.CSV, $env:PATH -split [IO.Path]::PathSeparator, Get-Command Get-Service.
Cleanup: Remove-Item ~/pslab/tmp/enc-*.txt, ~/pslab/tmp/ps51-*.txt, ~/pslab/tmp/crlf.txt.

Case 1: the CSV that Linux called binary

Problem: A nightly 5.1 job exported servers.csv with >; the Linux ETL saw NUL bytes and failed. Root cause: UTF-16 LE from 5.1's redirection. Fix: Export-Csv -Encoding UTF8 in 5.1 (with BOM) or move the job to pwsh 7 (UTF-8 no BOM); verify with Format-Hex.

Case 2: a module that imports on Windows but not in the Linux container

Problem: Import-Module opskit worked on laptops but failed in a Linux CI container. Root cause: the folder was OpsKit; Linux file names are case-sensitive, and an internal . $PSScriptRoot/public/x.ps1 used the wrong case too. Fix: exact case everywhere; run tests in a Linux container in CI (Lesson 8).

Case 3: the extra carriage return

Problem: A comparison $name -eq 'web-01' never matched for names read from a file edited on Windows. Root cause: -split "`n" left `r at the end of each line. Fix: Get-Content without -Raw (it strips line endings) or split on '\r?\n'; set a repository .gitattributes.

Common errors and fixes

Accented characters look like é or �

Encoding mismatch between writer and reader. Check bytes with Format-Hex; read with the right -Encoding; write UTF-8 deliberately.

Cannot find path '/home/…/SERVERS.CSV' (Linux) although it works on Windows

Case sensitivity. Use the exact name; Get-ChildItem -Name shows it.

Could not find a part of the path '…\~\…'

A .NET API got ~ or a relative path. Convert-Path first.

The term 'Get-Service' is not recognized (Linux/macOS)

Windows-only cmdlet. Guard with if ($IsWindows) or use native tools (systemctl).

A script with non-ASCII strings works in pwsh, garbles them in 5.1

5.1 reads BOM-less scripts as ANSI. Save the script as UTF-8 with BOM if 5.1 must run it.

Command-line exercises
1. Print each PATH entry on its own line on any OS.
$env:PATH -split [IO.Path]::PathSeparator
2. Write report.csv as UTF-8 with BOM and LF line endings for a picky consumer.
$lines = Import-Csv ~/pslab/data/servers.csv | ConvertTo-Csv -NoTypeInformation
[IO.File]::WriteAllText((Join-Path (Convert-Path ~/pslab/tmp) 'report.csv'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($true))
Scenario analysis
OpsKit must run on Windows laptops and in a Linux container in CI. List the checks you add to the code review.

No hard-coded \ or ;; Join-Path/Convert-Path before .NET; exact file-name case; no aliases; $IsWindows guards around Windows-only cmdlets; explicit -Encoding on files other tools read; split text on '\r?\n'; and a CI job that imports and tests the module on Linux.

Verified teaching videos

▶
PowerShell 7 Overview — John Savill's Technical Training
English · PowerShell 7 across platforms (title and channel verified)
▶
Getting Ready for DevOps with PowerShell and VS Code — John Savill's Technical Training
English · editor and workflow, including file encodings in VS Code (title and channel verified)

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: a backslash path breaks into pieces on a penguin's desk; Join-Path rebuilds it.
Narration: let Join-Path choose the separator.
Shot 2 · 20–50s
Visual: the bytes of 'café' in five rows, one row highlighted per encoding.
Narration: the same text, different bytes — Format-Hex tells the truth.
Shot 3 · 50–70s
Visual: a line 'web-01' with a hidden ␍ at the end fails an equality check.
Narration: CRLF leaves a carriage return behind.
Shot 4 · 70–90s
Visual: SERVERS.CSV found on Windows, not found on Linux.
Narration: Windows forgives case; Linux doesn't.
or score ≥ 70% on the Quiz

Module 8 · OpsKit v0.2: a packaged module published to a local repository

50:00 – 60:00 · Put it all together: validate the manifest against Public/, stage a clean copy, package or publish version 0.2.0, then install and import it by version in a clean session
10 minPublish-OpsKit.ps1★★★★★
Learning objectives
  • Describe OpsKit v0.2's final layout and what each file is for.
  • Write Publish-OpsKit.ps1: Test-ModuleManifest, export list = Public/ file names, clean staging, refusal to overwrite a released version, Compress-PSResource or Publish-PSResource.
  • Install the package into a module folder (as Install-PSResource does) and import it with -RequiredVersion / -MinimumVersion; read the errors when the version is not there.
  • Use the troubleshooting tree for “my module doesn't load / my command is missing”.
Prerequisites: Modules 1–5. Importance:★★★★★ (this is the milestone Lessons 5–8 build on)

What: OpsKit v0.2

PathRoleShips in the package?
~/pslab/OpsKit/OpsKit.psd1Identity: 0.2.0, RootModule, three exports, PowerShell 7.4+, Coreyes
~/pslab/OpsKit/OpsKit.psm1Loader: module state, dot-source Private + Public, exportyes
Public/Get-OpsConfig.ps1, Get-OpsServer.ps1, Test-OpsEndpoint.ps1The APIyes
Private/Resolve-OpsPath.ps1, ConvertTo-OpsServer.ps1Helpersyes (not exported)
~/pslab/scripts/Publish-OpsKit.ps1Release scriptno
~/pslab/out/OpsKit/Staged copy that gets packedis the package
~/pslab/repo/OpsKit.0.2.0.nupkgThe release—

Why: a release script instead of four commands typed by hand

Every production case in Modules 3 and 5 was a manual mistake: a missing export, a wildcard, a packed secret, an overwritten version. A script turns each lesson into a check that runs every time — and in Lesson 8 the same script runs in CI.

How: the release script

<#
.SYNOPSIS
    Validates, stages and packages OpsKit, then publishes it to the local folder repository.
.DESCRIPTION
    1. Test-ModuleManifest and a check that FunctionsToExport matches the files in Public/.
    2. Copies only the module files to ~/pslab/out/OpsKit (no tests, no .git, no notes).
    3. Publish-PSResource to the registered repository, or with -PackageOnly
       Compress-PSResource straight into the repository folder (no registration needed).
.EXAMPLE
    ./scripts/Publish-OpsKit.ps1 -PackageOnly
    ./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
    [string]$Source     = (Join-Path $HOME 'pslab' 'OpsKit'),
    [string]$Repository = 'PSLabLocal',
    [string]$RepoPath   = (Join-Path $HOME 'pslab' 'repo'),
    [switch]$PackageOnly
)
$ErrorActionPreference = 'Stop'

# 1) validate
$manifest = Test-ModuleManifest -Path (Join-Path $Source 'OpsKit.psd1')
$public   = @((Get-ChildItem -Path (Join-Path $Source 'Public') -Filter *.ps1).BaseName)
$declared = @($manifest.ExportedFunctions.Keys)
$diff     = Compare-Object -ReferenceObject $public -DifferenceObject $declared
if ($diff) {
    throw "FunctionsToExport does not match Public/: $(($diff | ForEach-Object { "$($_.InputObject) ($($_.SideIndicator))" }) -join ', ')"
}
Write-Verbose "OpsKit $($manifest.Version): manifest valid, exports $($declared -join ', ')"

# 2) stage only what belongs in the package
$stage = Join-Path $HOME 'pslab' 'out' 'OpsKit'
if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
$null = New-Item -ItemType Directory -Path $stage -Force
Copy-Item -Path (Join-Path $Source 'OpsKit.psd1'), (Join-Path $Source 'OpsKit.psm1') -Destination $stage
Copy-Item -Path (Join-Path $Source 'Public'), (Join-Path $Source 'Private') -Destination $stage -Recurse

# 3) package / publish
$null = New-Item -ItemType Directory -Path $RepoPath -Force
$nupkg = Join-Path $RepoPath "OpsKit.$($manifest.Version).nupkg"
if (Test-Path -LiteralPath $nupkg) {
    throw "Version $($manifest.Version) is already in $RepoPath. Bump ModuleVersion instead of overwriting a release."
}
if ($PackageOnly) {
    Compress-PSResource -Path $stage -DestinationPath $RepoPath
} else {
    Publish-PSResource -Path $stage -Repository $Repository
}
Get-Item -LiteralPath $nupkg

When: install and import by version

  • With a registered repository: Install-PSResource OpsKit -Version 0.2.0 -Repository PSLabLocal (Module 5, optional).
  • Without one (this lab): unpack the .nupkg into ~/pslab/modules/OpsKit/0.2.0/ and remove the NuGet bookkeeping — the same layout an install produces — then put ~/pslab/modules on PSModulePath for the session.
  • Consumers pin: Import-Module OpsKit -RequiredVersion 0.2.0 in scripts, #Requires -Modules @{ ModuleName = 'OpsKit'; RequiredVersion = '0.2.0' }, or RequiredModules in their own manifest.
Common misconceptions① “Packing the source folder is fine for a lab” — the habit ships secrets later; stage. ② “If the version exists, overwrite it” — releases are immutable; the script refuses. ③ “Tested in my session = tested” — your session has dot-sourced leftovers and old module versions; test in pwsh -NoProfile. ④ “-MinimumVersion 0.3.0 will fall back to 0.2.0” — it fails, which is what you want.

Flowchart: the v0.2 release pipeline

Test-ModuleManifestsyntax · version Exports = Public/Compare-Object Stage~/pslab/out/OpsKit Version exists?yes → stop Pack / PublishOpsKit.0.2.0.nupkg Install layoutModules/OpsKit/0.2.0/ (7 files) Clean pwsh -NoProfileImport-Module OpsKit -RequiredVersion 0.2.0 Acceptance: version 0.2.0 · exactly 3 exports · helpers hidden · loaded from the package · prod = 6 serversThe integrated lab automates these checks in Test-OpsKitPackage.ps1
Figure 8-1: each box is a lesson learned in Modules 1–5, turned into an automatic check

Release pipeline: which run passes?

Below the animation is the interactive troubleshooting tree for module loading problems.

Ready.

Interactive troubleshooting tree: my module or command doesn't load

Command table

CommandPurposeNotes
./scripts/Publish-OpsKit.ps1 -PackageOnly -VerboseValidate, stage, pack into ~/pslab/repoNo registration needed
./scripts/Publish-OpsKit.ps1 -Repository PSLabLocalSame, publish to a registered feedOptional
Expand-Archive pkg.nupkg -DestinationPath Modules/OpsKit/0.2.0Install layout by handThen delete _rels, package, [Content_Types].xml, *.nuspec
Import-Module OpsKit -RequiredVersion 0.2.0Exact versionFails if absent
Get-Module OpsKit -ListAvailableWhat is installed where
Set-Location ~/pslab
./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose | Format-Table Name, Length
./scripts/Publish-OpsKit.ps1 -PackageOnly
Get-ChildItem ~/pslab/out/OpsKit -Recurse -File -Name
VERBOSE: OpsKit 0.2.0: manifest valid, exports Get-OpsConfig, Get-OpsServer, Test-OpsEndpoint
VERBOSE: The newly created nuspec is: C:\WINDOWS\TEMP\0e398648-9649-48c2-a327-696c3db84506\OpsKit.nuspec
VERBOSE: Successfully packed the resource into a .nupkg
VERBOSE: Deleting temporary directory 'C:\WINDOWS\TEMP\0e398648-9649-48c2-a327-696c3db84506'

Name               Length
----               ------
OpsKit.0.2.0.nupkg   6330

Exception: Version 0.2.0 is already in C:\Users\labadmin\pslab\repo. Bump ModuleVersion instead of overwriting a release.
OpsKit.psd1
OpsKit.psm1
Private\ConvertTo-OpsServer.ps1
Private\Resolve-OpsPath.ps1
Public\Get-OpsConfig.ps1
Public\Get-OpsServer.ps1
Public\Test-OpsEndpoint.ps1

In the console, the throw appears as Exception: …\Publish-OpsKit.ps1:44 followed by the message box; it is shortened here. The VERBOSE lines from Compress-PSResource show the temporary folder where the nuspec is generated.

# The export check catches a forgotten manifest update
Set-Content ~/pslab/OpsKit/Public/Get-OpsHealth.ps1 -Value 'function Get-OpsHealth { "todo" }'
./scripts/Publish-OpsKit.ps1 -PackageOnly
Remove-Item ~/pslab/OpsKit/Public/Get-OpsHealth.ps1
Exception: FunctionsToExport does not match Public/: Get-OpsHealth (<=)
# "Install": unpack to the layout Install-PSResource creates, then import by version
$dest = Join-Path ~/pslab/modules 'OpsKit' '0.2.0'
Expand-Archive ~/pslab/repo/OpsKit.0.2.0.nupkg -DestinationPath $dest -Force
Remove-Item -LiteralPath (Join-Path $dest '_rels'), (Join-Path $dest 'package'),
                         (Join-Path $dest '[Content_Types].xml'), (Join-Path $dest 'OpsKit.nuspec') -Recurse
$env:PSModulePath = (Join-Path $HOME 'pslab' 'modules') + [IO.Path]::PathSeparator + $env:PSModulePath
Get-Module OpsKit -ListAvailable | Format-Table Name, Version, ModuleType, @{ n = 'ExportedCommands'; e = { $_.ExportedCommands.Keys -join ', ' } }
Get-OpsServer -Environment staging | Format-Table Name, Env, IP          # auto-loads OpsKit
Get-Module OpsKit | Format-Table Name, Version, ModuleType
Import-Module OpsKit -MinimumVersion 0.3.0
Import-Module OpsKit -RequiredVersion 0.2.0 -Force -PassThru | Format-Table Name, Version
(Get-Command Get-OpsServer).Module.ModuleBase
Name   Version ModuleType ExportedCommands
----   ------- ---------- ----------------
OpsKit 0.2.0       Script Get-OpsConfig, Get-OpsServer, Test-OpsEndpoint

Name   Env     IP
----   ---     --
web-01 staging 10.20.1.31
api-01 staging 10.20.1.32
db-01  staging 10.20.1.33

Name   Version ModuleType
----   ------- ----------
OpsKit 0.2.0       Script

Import-Module: The specified module 'OpsKit' with version '0.3.0' was not loaded because no valid module file was found in any module directory.

Name   Version
----   -------
OpsKit 0.2.0

C:\Users\labadmin\pslab\modules\OpsKit\0.2.0

How to verify: the commands auto-loaded from the installed copy (ModuleBase under modules\OpsKit\0.2.0), not from your source folder. Common mistake: testing against ~/pslab/OpsKit and shipping something else. Production use: the same steps run in CI against the built package (Lesson 8).

Goal: Release OpsKit 0.2.0 into ~/pslab/repo and consume it by version. Environment: OpsKit from Modules 2–3. Cost: none; nothing outside ~/pslab changes.

Save the release script as ~/pslab/scripts/Publish-OpsKit.ps1 (Principles tab). If Module 5 left ~/pslab/repo/OpsKit.0.2.0.nupkg behind, delete it first.
Release: ./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose; run it a second time and read the refusal.
Break the export contract with a new Public/Get-OpsHealth.ps1, watch the script stop, remove the file.
Install and import by version with the commands from the Commands tab; then in a brand-new process:
pwsh -NoProfile -Command '$env:PSModulePath = (Join-Path $HOME pslab modules) + [IO.Path]::PathSeparator + $env:PSModulePath; Import-Module OpsKit -RequiredVersion 0.2.0; (Get-Module OpsKit).Version.ToString(); (Get-OpsServer -Environment prod).Count'
0.2.0
6
Optional (changes user state): register PSLabLocal and run ./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal after bumping to 0.2.1 with Update-PSModuleManifest; undo with Unregister-PSResourceRepository PSLabLocal.
Cleanup: keep ~/pslab/repo and ~/pslab/modules/OpsKit — Lesson 5 starts from 0.2.0. ~/pslab/out can be deleted at any time.

Case 1: a bug in the test, found by the test

Problem: While writing this lesson's acceptance script, the “files in package” check reported 8 instead of 7. Root cause: Remove-Item -Path …\[Content_Types].xml treats [Content_Types] as a wildcard character class (Lesson 1, Module 7), so the file was silently not deleted. Fix: -LiteralPath. The test caught it only because it counted files exactly — make acceptance checks precise.

Case 2: “it works from source”

Problem: A release passed every local run but failed for users: a Private file was missing from the package. Root cause: tests imported ~/src/Module, not the built package; the build's copy step had a typo. Fix: test the artifact you ship (the integrated lab does exactly that).

Case 3: version drift between scripts

Problem: After OpsKit 0.3.0 appeared on the feed, an old scheduled script broke because a default changed. Root cause: it imported OpsKit without a version. Fix: pin in automation (#Requires … RequiredVersion), upgrade deliberately with a changelog.

Common errors and fixes

Version 0.2.0 is already in … Bump ModuleVersion

Intended. Update-PSModuleManifest -Path ~/pslab/OpsKit/OpsKit.psd1 -ModuleVersion 0.2.1, or delete the lab package if you are only practising.

FunctionsToExport does not match Public/: X (<=) or (=>)

<=: file exists, not exported → add it to the manifest. =>: exported name without a file → remove it or create the file.

The specified module 'OpsKit' with version 'x' was not loaded …
Get-Module OpsKit -ListAvailable | Format-Table Version, ModuleBase
$env:PSModulePath -split [IO.Path]::PathSeparator
Commands come from the source folder instead of the installed copy

(Get-Command Get-OpsServer).Module.ModuleBase. Remove the module, start a new session, import by name/version.

Command-line exercises
1. Bump OpsKit to 0.2.1 and release it without touching 0.2.0.
Update-PSModuleManifest -Path ~/pslab/OpsKit/OpsKit.psd1 -ModuleVersion 0.2.1 -ReleaseNotes '0.2.1: …'
./scripts/Publish-OpsKit.ps1 -PackageOnly
Get-ChildItem ~/pslab/repo -Name
2. Make a script refuse to run unless OpsKit 0.2.0 exactly is available.
#Requires -Modules @{ ModuleName = 'OpsKit'; RequiredVersion = '0.2.0' }
Scenario analysis
Your release script passes, but a colleague says “Get-OpsServer is not recognized” after installing. Walk through the diagnosis.

① Which PowerShell? ($PSVersionTable; the manifest requires 7.4.) ② Is it installed where PSModulePath looks? (Get-Module OpsKit -ListAvailable.) ③ Does the installed manifest export it? ((Get-Module OpsKit -ListAvailable).ExportedFunctions.) ④ Is auto-loading off or the session stale? (Import-Module OpsKit -RequiredVersion … in a new session.) ⑤ Linux? Folder case must be OpsKit. Use the troubleshooting tree in the Animation tab.

Verified teaching videos

▶
Getting Ready for DevOps with PowerShell and VS Code — John Savill's Technical Training
English · source control and tooling around a module (title and channel verified)
▶
PowerShell Master Class - Automation — John Savill's Technical Training
English · title and channel verified

No verified video walks through packaging a module with PSResourceGet into a folder feed; this module's script and outputs are the reference.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: five gates in a row (manifest, exports, stage, version, pack); a package rolls through.
Narration: a release is a sequence of checks.
Shot 2 · 20–45s
Visual: a second 0.2.0 package bounces off the shelf.
Narration: never overwrite a version.
Shot 3 · 45–70s
Visual: the package unfolds into Modules/OpsKit/0.2.0 and a fresh terminal imports it.
Narration: test the artifact, in a clean session, by version.
Shot 4 · 70–90s
Visual: roadmap 0.2 → 0.3 (errors) → 0.4 (parallel) → 0.5 (cloud) → 1.0 (tests).
Narration: OpsKit is now a real module; next lesson makes it robust.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 4 key points: module discovery, script modules, manifests, PSResourceGet, repositories, providers, cross-platform rules and the release flow
PowerShell 7.6Copyable

1. Finding and loading modules

$env:PSModulePath -split [IO.Path]::PathSeparator
Get-Module                          # loaded
Get-Module X -ListAvailable         # installed (all versions)
Import-Module X -RequiredVersion 1.2.3 -PassThru
Import-Module ./X -Force            # reload after edits
#Requires -Modules @{ ModuleName='X'; ModuleVersion='5.0.0' }
Module\Command                      # qualified call

2. Script module

# X.psm1
$script:State = $null               # module scope
foreach ($f in @(Get-ChildItem $PSScriptRoot/Private/*.ps1) +
               @(Get-ChildItem $PSScriptRoot/Public/*.ps1)) { . $f.FullName }
Export-ModuleMember -Function (Get-ChildItem $PSScriptRoot/Public/*.ps1).BaseName
& (Get-Module X) { $script:State } # peek inside (debug)

3. Manifest

New-ModuleManifest X.psd1 -RootModule X.psm1 -ModuleVersion 0.2.0 `
  -FunctionsToExport a,b -CmdletsToExport @() -AliasesToExport @() `
  -PowerShellVersion 7.4 -CompatiblePSEditions Core
Test-ModuleManifest X.psd1
Update-PSModuleManifest X.psd1 -ModuleVersion 0.2.1
# never: FunctionsToExport = '*'

4. PSResourceGet

Find-PSResource X -Version '[5.0,6.0)'
Save-PSResource X -Version 1.2.3 -Path ~/pslab/modules -IncludeXml -TrustRepository
Install-PSResource X -Version 1.2.3 -Scope CurrentUser
Update-PSResource X; Uninstall-PSResource X -Version 1.2.3
Get-InstalledPSResource [-Path dir]
# '5.7' = exactly 5.7.0 · '[5.7,]' = 5.7 or later

5. Repositories and publishing

Compress-PSResource -Path ./out/X -DestinationPath ~/pslab/repo
Register-PSResourceRepository -Name Local -Uri (Convert-Path ~/pslab/repo) -Trusted
Publish-PSResource -Path ./out/X -Repository Local
Install-PSResource -RequiredResourceFile requirements.psd1
Save-PSResource X -Version 1.2.3 -AsNupkg -Path ~/pslab/repo   # mirror
Unregister-PSResourceRepository Local

6. Providers and drives

Get-PSProvider; Get-PSDrive
Get-ChildItem Env:\PS*; $env:X = 'v'; Remove-Item Env:\X
Get-ChildItem Function:\*-Ops*; New-Item Alias:\gos -Value Get-OpsServer
Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' CurrentBuild
Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
New-PSDrive Lab FileSystem ~/pslab/data; Convert-Path Lab:\servers.csv

7. Cross-platform

Join-Path $HOME pslab data servers.csv
Split-Path $p -Leaf / -LeafBase / -Extension / -Parent
[IO.File]::ReadAllText((Convert-Path ~/x.txt))
$IsWindows; $IsLinux; $IsMacOS
Set-Content f -Value $t -Encoding utf8NoBOM   # utf8BOM / unicode / 1252
Format-Hex f                                   # the truth
$text -split '\r?\n'; $env:PATH -split [IO.Path]::PathSeparator

8. Release flow (OpsKit v0.2)

./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose
#  manifest valid → exports = Public/ → stage → refuse existing version → pack
Expand-Archive repo/OpsKit.0.2.0.nupkg modules/OpsKit/0.2.0   # install layout
pwsh -NoProfile -Command 'Import-Module OpsKit -RequiredVersion 0.2.0'
./Test-OpsKitPackage.ps1; $LASTEXITCODE        # 0 = ship it

Integrated lab + final quiz

Write ~/pslab/Test-OpsKitPackage.ps1: unpack the released package the way an install does, import it by version in a clean child pwsh, and verify version, exports, privacy and behavior with meaningful exit codes
about 25 minLocal onlyIntegrates M1–M8

Scenario

Before anyone installs OpsKit 0.2.0, your team wants a gate that tests the package, not the source folder. The script must: find ~/pslab/repo/OpsKit.<version>.nupkg (exit 2 if missing); unpack it into a temporary module root in the install layout; start a clean pwsh -NoProfile -NonInteractive whose PSModulePath sees that root; import OpsKit with -RequiredVersion; report checks as objects; exit 0 when all pass and 1 otherwise; and clean up after itself.

The script (M1, M2, M3, M5, M6, M7, M8) — save as ~/pslab/Test-OpsKitPackage.ps1:
<#
.SYNOPSIS
    Acceptance test for the OpsKit package: unpacks the .nupkg the way an install does
    and imports it by version in a clean child pwsh.
.DESCRIPTION
    Exit codes: 0 all checks passed; 1 at least one check failed; 2 package not found.
.EXAMPLE
    ./Test-OpsKitPackage.ps1
    ./Test-OpsKitPackage.ps1 -Version 0.2.0 -RepoPath ~/pslab/repo
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
    [version]$Version = '0.2.0',
    [string]$RepoPath = (Join-Path $HOME 'pslab' 'repo')
)

$nupkg = Join-Path $RepoPath "OpsKit.$Version.nupkg"
if (-not (Test-Path -LiteralPath $nupkg)) {
    Write-Error "Test-OpsKitPackage: package not found: $nupkg"
    exit 2
}

# 1) Unpack into <root>/OpsKit/<version>, like Install-PSResource does, minus the NuGet metadata.
$root   = Join-Path $HOME 'pslab' 'tmp' 'pkgtest'
$target = Join-Path $root 'OpsKit' $Version
if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force }
Expand-Archive -LiteralPath $nupkg -DestinationPath $target
Remove-Item -LiteralPath (Join-Path $target '_rels'), (Join-Path $target 'package'),
                         (Join-Path $target '[Content_Types].xml'), (Join-Path $target 'OpsKit.nuspec') -Recurse -Force

# 2) Import it by version in a clean child process that sees only this module root + the defaults.
$probe = @'
$ErrorActionPreference = 'Stop'
$m = Import-Module OpsKit -RequiredVersion '{0}' -PassThru
[pscustomobject]@{{
    Version   = "$($m.Version)"
    Exported  = (($m.ExportedFunctions.Keys | Sort-Object) -join ',')
    Private   = [bool](Get-Command ConvertTo-OpsServer, Resolve-OpsPath -ErrorAction Ignore)
    FromPath  = $m.ModuleBase.StartsWith('{1}')
    ProdCount = @(Get-OpsServer -Environment prod).Count
    Typed     = (Get-OpsServer -Name edge-01).Roles.Count
}} | ConvertTo-Json -Compress
'@ -f $Version, $root
$saved = $env:PSModulePath
try {
    $env:PSModulePath = $root + [IO.Path]::PathSeparator + $env:PSModulePath
    $json = pwsh -NoProfile -NonInteractive -Command $probe
    $childExit = $LASTEXITCODE
} finally {
    $env:PSModulePath = $saved
}
$r = if ($childExit -eq 0) { $json | ConvertFrom-Json } else { [pscustomobject]@{} }

function New-Check([string]$Name, $Expected, $Actual) {
    [pscustomobject]@{ Check = $Name; Expected = "$Expected"; Actual = "$Actual"; Passed = "$Expected" -eq "$Actual" }
}
$results = @(
    New-Check 'child import exit code'   0 $childExit
    New-Check 'module version'           $Version $r.Version
    New-Check 'exported functions'       'Get-OpsConfig,Get-OpsServer,Test-OpsEndpoint' $r.Exported
    New-Check 'private helpers hidden'   $false $r.Private
    New-Check 'loaded from the package'  $true $r.FromPath
    New-Check 'prod servers'             6 $r.ProdCount
    New-Check 'edge-01 roles typed'      2 $r.Typed
    New-Check 'files in package'         7 @(Get-ChildItem -LiteralPath $target -Recurse -File).Count
)
$results
Remove-Item -LiteralPath $root -Recurse -Force

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

Details worth noticing: the probe is a format string, so literal braces are doubled (@{{); $env:PSModulePath is changed only around the child call and restored in finally; NuGet bookkeeping files are removed with -LiteralPath because [Content_Types] is a wildcard pattern for -Path (Module 8, Case 1 — this bug happened while writing the lab).

Run it (after Module 8 built OpsKit.0.2.0.nupkg):
Set-Location ~/pslab
./Test-OpsKitPackage.ps1 | Format-Table Check, Expected, Actual, Passed -AutoSize; "exit=$LASTEXITCODE"
Check                   Expected                                     Actual                                       Passed
-----                   --------                                     ------                                       ------
child import exit code  0                                            0                                              True
module version          0.2.0                                        0.2.0                                          True
exported functions      Get-OpsConfig,Get-OpsServer,Test-OpsEndpoint Get-OpsConfig,Get-OpsServer,Test-OpsEndpoint   True
private helpers hidden  False                                        False                                          True
loaded from the package True                                         True                                           True
prod servers            6                                            6                                              True
edge-01 roles typed     2                                            2                                              True
files in package        7                                            7                                              True

exit=0
Failure paths:
./Test-OpsKitPackage.ps1 -Version 0.3.0; "exit=$LASTEXITCODE"
pwsh -NoProfile -NonInteractive -File ./Test-OpsKitPackage.ps1 | Out-Null; "exit=$LASTEXITCODE"
Test-Path ~/pslab/tmp/pkgtest
Test-OpsKitPackage.ps1: Test-OpsKitPackage: package not found: C:\Users\labadmin\pslab\repo\OpsKit.0.3.0.nupkg
exit=2
exit=0
False

With the -Path bug still in the script, the same run printed files in package 7 8 False, the warning 1 check(s) failed: files in package and exit=1 — the failure path works too.

Acceptance criteria

Open-ended self-check

1. Explain, step by step, what happens when a fresh session runs Get-OpsServer with ~/pslab/modules on PSModulePath.

No loaded command matches; auto-loading scans PSModulePath in order, finds ~/pslab/modules/OpsKit/0.2.0/OpsKit.psd1, reads FunctionsToExport (data only) and sees the name; it checks PowerShellVersion, then runs OpsKit.psm1 in a new module scope (sets $script: state, dot-sources Private and Public, Export-ModuleMember); the export filter (psm1 ∩ manifest) imports three functions; the command runs and calls private helpers inside module scope.

2. Why do the manifest's export list and the psm1's Export-ModuleMember both exist, and which wins?

The manifest list is static metadata for discovery, installers and galleries; Export-ModuleMember controls what the code exports at runtime. A function is exported only if both allow it.

3. Name three ways a module can “work on my machine” but not on a server.

A different version earlier on PSModulePath (or Pester 3.4 in-box); profile-dependent state or drives; case-sensitive paths on Linux; repository not registered or untrusted for the service account; encodings/line endings of data files.

4. What would you change in Test-OpsKitPackage.ps1 to run it in CI on Linux?

Nothing path-related — it uses Join-Path and [IO.Path]::PathSeparator; just make sure the data folder exists (or point Get-OpsServer -Path to a test CSV), and run it with pwsh -File so the exit code reaches the CI system.

Sources and version notes

Version facts were checked on 2026-11-24 against Microsoft Learn, the PowerShell Gallery and YouTube oEmbed; command outputs were produced on PowerShell 7.6.10 and Windows PowerShell 5.1.26100
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Bundled package toolspwsh 7.6.10 ships Microsoft.PowerShell.PSResourceGet 1.2.1 (Binary), PowerShellGet 2.2.5, PackageManagement 1.4.8.1, PSReadLine 2.4.5, Microsoft.PowerShell.ThreadJob 2.2.0; ThreadJob\Start-ThreadJob fails in 7.6This lesson's runs; What's New in PowerShell 7.6
Module discoveryPSModulePath entries and order on Windows; auto-loading; first PSModulePath entry containing a module wins over a newer version in a later entry; Pester 3.4.0 in the Windows PowerShell folder; assembly reload failure when switching Pester 6.2.0 → 5.9.1about_Modules; about_PSModulePath; about_Requires; runs
Script modulesWithout Export-ModuleMember: functions exported, variables and aliases not; module scope state; -Force reloadExport-ModuleMember; PowerShell 101: Script modules; runs
ManifestsNew-ModuleManifest output; wildcard FunctionsToExport hides dot-sourced functions from discovery; six error messages; 5.1 blocked by PowerShellVersion, not by CompatiblePSEditionsabout_Module_Manifests; New-ModuleManifest; Test-ModuleManifest; runs
PSResourceGetNuGet range behavior (exact 5.7, [x, ], 5.* includes 6.x); a range resolved to the lowest match for PSScriptAnalyzer; untrusted repository + -NonInteractive error; -IncludeXml needed for Get-InstalledPSResource -Path. Gallery on 2026-11-24: Pester 6.2.0 / 5.9.1, PSScriptAnalyzer 1.25.0, SecretManagement 1.1.2Install-PSResource (version syntax, required-resource formats, scopes); Save-PSResource; about_PSResourceGet; runs
RepositoriesFolder, Azure Artifacts, GitHub Packages, JFrog, MyGet, NuGet.Server, ACR configurations and limitations; Gallery to be treated as untrusted; 1.3 previews add the Microsoft Artifact Registry as a default repositorySupported repository configurations; Working with local PSRepositories; Publish-PSResource; Compress-PSResource
ProvidersProvider capabilities, Env/Variable/Function/Alias item operations, read-only Cert: and registry queries, -Filter error on Env:about_Providers and the per-provider about topics; runs
Cross-platformByte-level encodings in 7.6 and 5.1 (lab machine ACP 65001), CRLF splitting, ~ in .NET calls, case-insensitive Windows lookupabout_Character_Encoding; Writing portable modules; runs
OpsKit v0.2Publish-OpsKit.ps1 and Test-OpsKitPackage.ps1 run on 7.6.10; package 6.3 KB, 7 module files; all 8 acceptance checks passActual runs for this lesson

Video verification notes

Only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24 are listed. The John Savill videos were found in his “PowerShell Master Class” playlist (PLlVtbbG169nFq_hR7FcMYg32xsSAObuq8, also verified via oEmbed):

oEmbed verifies titles and channels only; the videos were not watched segment by segment, and the “meta” lines describe the topic suggested by the title. Most predate PowerShell 7.6 and PSResourceGet; where they show Install-Module or Windows PowerShell 5.1 behavior, this lesson is authoritative. Web searches on 2026-11-24 found no verifiable video on PSResourceGet 1.2, module manifests' export lists, or Compress-PSResource.

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: “Actual output (7.6.10)” was produced on Windows 11 (build 26300) with pwsh 7.6.10 in a child process whose HOME/USERPROFILE pointed at a scratch folder (so ~/pslab was isolated) and whose PSModulePath started from the Windows default machine value; paths were replaced with C:\Users\labadmin\… and table widths adjusted where a long scratch path had wrapped a column. Error records are shown in the one-line form an interactive console prints.
  • Not run (state-changing): Register-PSResourceRepository, Publish-PSResource to a registered repository, Install-PSResource, Update-PSResource, Uninstall-PSResource, Install-PSResource -RequiredResourceFile, Set-PSResourceRepository. PSResourceGet 1.2.1 keeps its repository list in a fixed per-user file (it ignored a redirected LOCALAPPDATA), so these could not be isolated; their outputs are labeled “Expected”. The package itself was verified with Compress-PSResource and by unpacking it into the install layout.
  • Not run on Linux/macOS: case-sensitivity, : separators, Linux module paths and missing Windows cmdlets are taken from the documentation and labeled “Expected”.
  • The 5.1 Set-Content encoding result depends on the system ANSI code page; the lab machine uses 65001 (UTF-8), so the 1252 behavior is shown with -Encoding 1252 in pwsh instead.
  • The range-resolution quirk (lowest match for PSScriptAnalyzer, newest for Pester) was observed on PSResourceGet 1.2.1 against the PowerShell Gallery on 2026-11-24; the cause was not investigated and may change in later versions.
  • The animations simplify: they omit the module analysis cache details, nested modules, ScriptsToProcess, and NuGet dependency resolution.