PowerShell Lesson 4: Modules, Packages, Providers and Cross-Platform Environments
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.- Explain the module kinds (script, binary, manifest), read
$env:PSModulePathon any platform with-split [IO.Path]::PathSeparator, and predict which version auto-loading andImport-Modulepick — including the in-box Pester 3.4.0 trap on Windows. - Build a script module: an
.psm1that dot-sourcesPublic/andPrivate/, exports only public functions, and keeps state in module scope ($script:) that callers cannot see. - Write a manifest with
New-ModuleManifest:RootModule,ModuleVersion, explicitFunctionsToExport(and why wildcards break auto-loading),RequiredModules,PowerShellVersion/CompatiblePSEditions; validate it withTest-ModuleManifestand 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/*-ItemPropertycmdlets, and create your own drive withNew-PSDrive. - Write cross-platform code:
Join-Pathinstead of\, case-sensitive file systems,$IsWindows, UTF-8 without BOM vs Windows PowerShell 5.1 encodings (proved withFormat-Hex), CRLF vs LF, and$env:PATHseparators. - Ship OpsKit v0.2: validate, stage, package, publish to
~/pslab/repo, and prove with an acceptance script that a cleanpwshimports exactly version 0.2.0 with exactly three public commands.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interactive | Lab (~/pslab) |
|---|---|---|---|---|---|
| 0 | Before Class | Prep | Check OpsKit v0.1 from Lesson 3 (or recreate it), create ~/pslab/repo, ~/pslab/modules, ~/pslab/out; confirm PSResourceGet 1.2.x | Self-check checklist | OpsKit v0.1 warm-up run |
| 1 | 00–06 | Modules | Script / 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 trap | Module resolver: which module and version load? | Pester 3.4 vs 6.2 side by side in ~/pslab/modules |
| 2 | 06–13 | Script module | OpsKit.psm1; dot-sourcing Public/ + Private/; Export-ModuleMember; default exports; module scope and $script:; & (Get-Module X) { }; InModuleScope preview | What happens inside Import-Module | Convert OpsKit v0.1 to OpsKit.psm1 |
| 3 | 13–21 | Manifest | New-ModuleManifest; RootModule; ModuleVersion; FunctionsToExport without wildcards; RequiredModules; PowerShellVersion / CompatiblePSEditions; PrivateData.PSData; Test-ModuleManifest | Manifest processing pipeline | Write OpsKit.psd1 and reproduce six manifest errors |
| 4 | 21–28 | PSResourceGet | Find-/Install-/Save-/Update-/Uninstall-PSResource, Get-InstalledPSResource; scopes; NuGet ranges; trust; v2 comparison | From -Version range to folder on disk | Save Pester and PSScriptAnalyzer into ~/pslab/modules |
| 5 | 28–35 | Repositories | Folder repositories; Register-PSResourceRepository; Compress- / Publish-PSResource; .nupkg anatomy; pinned installs; -RequiredResourceFile; Azure Artifacts / GitHub Packages | Publish → feed → install → import | Build OpsKit.0.2.0.nupkg in ~/pslab/repo |
| 6 | 35–42 | Providers and drives | Get-PSProvider, Get-PSDrive; Env:, Variable:, Function:, Alias:, Cert:, HKCU:/HKLM:; New-PSDrive; *-Item, *-ItemProperty; provider capabilities; PSPath | Path → provider → item | A Lab: drive and read-only registry/cert queries |
| 7 | 42–50 | Cross-platform | Join-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 cmdlets | One script, Windows vs Linux | Byte-level encoding comparison 7.6 vs 5.1 |
| 8 | 50–60 | OpsKit v0.2 | Final layout; Publish-OpsKit.ps1 (validate → stage → pack/publish); install layout; import by version; release rules | Release pipeline + troubleshooting tree | Publish 0.2.0 and import it by version |
| — | After Class | Cheat sheet · Integrated lab | Test-OpsKitPackage.ps1: unpack the package the way an install does, import it by version in a clean child pwsh, verify exports, privacy, version and behavior | Final quiz (12 questions) | All eight acceptance checks pass; exit code 0 |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Find and load modules; predict the version | ✓ | · | ✓ | ✓ | · | · | · | ✓ | $env:PSModulePath, Get-Module -ListAvailable, Import-Module -RequiredVersion | M1, M8 |
| Build a script module with private code | · | ✓ | ✓ | · | · | ✓ | · | ✓ | .psm1, Export-ModuleMember, $script: | M2 |
| Write and validate a manifest | · | · | ✓ | · | ✓ | · | · | ✓ | New-ModuleManifest, Test-ModuleManifest, Update-PSModuleManifest | M3, 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, -RequiredResourceFile | M5, integrated lab |
| Navigate providers and drives | · | ✓ | · | · | · | ✓ | ✓ | · | Get-PSProvider, New-PSDrive, Get-ItemProperty | M6 |
| Write portable paths, encodings and line endings | ✓ | · | · | · | · | ✓ | ✓ | ✓ | Join-Path, $IsWindows, -Encoding utf8BOM, Format-Hex | M7 |
| Release a versioned module and prove it works | · | ✓ | ✓ | · | ✓ | · | · | ✓ | Compress-PSResource, clean pwsh -NoProfile, acceptance checks | M8, integrated lab |
Excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
| Advanced functions, parameter validation, pipeline input, scope rules for functions | Prerequisite; this lesson packages functions you already have | Lesson 3: Functions, Scope and Advanced Functions |
try/catch, terminating errors, -WhatIf/SupportsShouldProcess, logging | Error handling is the next layer of OpsKit (v0.3) | Lesson 5 |
| Binary modules in C#, class-based modules, DSC resources | Need .NET development; rarely written by operations teams | Microsoft Learn: “Writing a Windows PowerShell module” |
Remoting a module to many machines, Import-Module -PSSession | Multi-machine administration | Lesson 6 |
| SecretManagement vaults, credentials for private feeds in CI | Shown only as an overview here; secrets are Lesson 7's topic | Lesson 7 |
Pester tests (InModuleScope), PSScriptAnalyzer, code signing, CI release pipeline | Quality and release | Lesson 8 |
How to use these materials
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Read “Principles” and “Animation” first, then do the “Lab” in
~/pslab. Modules 2, 3, 5 and 8 build OpsKit v0.2 step by step — do them in order.A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
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
~/pslab/OpsKit (or recreate it below), create the folders this lesson publishes into, and confirm which PSResourceGet you have- Lessons 1–3, or equivalent: you can write an advanced function with
[CmdletBinding()]andparam(), and you know what dot-sourcing does. - PowerShell 7.6 and the dataset in
~/pslab/datafrom Lesson 1, Module 0 (./New-LabData.ps1rebuilds it at any time). - Internet access to
www.powershellgallery.comfor 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
| Folder | Purpose 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
~/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
- Name the three module kinds — script (
.psm1), binary (.dll), manifest (.psd1describing one of the others) — and recognise them inGet-Moduleoutput. - Read
$env:PSModulePathwith-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) andGet-Module -ListAvailable(installed), and useImport-Module -Force -PassThru,-RequiredVersionand#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.
What: three kinds of module
| Kind | Root file | Contains | Example on 7.6.10 |
|---|---|---|---|
| Script module | Name.psm1 | PowerShell functions, variables, aliases; loaded by running the .psm1 in its own module scope | PSReadLine 2.4.5 (script wrapper + dll), Pester, your OpsKit |
| Binary module | Name.dll | Compiled cmdlets (.NET classes) | Microsoft.PowerShell.PSResourceGet 1.2.1 (RootModule = './Microsoft.PowerShell.PSResourceGet.dll'), Microsoft.PowerShell.ThreadJob |
| Manifest module | Name.psd1 | A data file that describes the module: version, root/nested modules, exports, requirements. ModuleType shows Manifest when there is no single script or binary root | CimCmdlets, 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 / macOS | Purpose |
|---|---|---|---|
| 1 | $HOME\Documents\PowerShell\Modules | ~/.local/share/powershell/Modules | CurrentUser installs |
| 2 | $env:ProgramFiles\PowerShell\Modules | /usr/local/share/powershell/Modules | AllUsers installs |
| 3 | $PSHOME\Modules | $PSHOME/Modules | Modules 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
- 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. - If several versions are installed,
Import-Module Nameand 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,-MaximumVersionpin it. Get-Modulelists what is loaded in this session;Get-Module -ListAvailablelists what is installed on PSModulePath (it does not import anything).Import-Module Xdoes nothing if X is already loaded —-Forcere-runs it.-PassThrureturns the module object so you can see what you got.$PSModuleAutoLoadingPreference = 'None'disables auto-loading in a session;#Requires -Moduleslets 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.
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
Version selection: same name, three folders
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.
#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
| Command | Purpose | Notes |
|---|---|---|
$env:PSModulePath -split [IO.Path]::PathSeparator | Where modules are searched | Portable split (; / :) |
Get-Module | Loaded modules | Session only |
Get-Module Name -ListAvailable | Installed modules, all versions | Does not import |
Import-Module Name -PassThru | Import and return the module object | See Version, ModuleBase |
Import-Module Name -Force | Re-run the module | Use after editing a module; cannot unload assemblies |
Import-Module Name -RequiredVersion 5.9.1 | Exact version | Also -MinimumVersion, -MaximumVersion |
Remove-Module Name | Unload commands from the session | Assemblies stay loaded |
#Requires -Modules @{ ModuleName='X'; ModuleVersion='5.0.0' } | Script prerequisite | ModuleVersion = minimum; RequiredVersion = exact |
Module\Command | Module-qualified call | Bypasses shadowing; auto-loads |
$PSModuleAutoLoadingPreference | All (default), ModuleQualified, None | Diagnostics; 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.
$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).
pwsh -NoProfile -Command 'Get-Module | ForEach-Object Name; "--"; $null = Get-PSResourceRepository; Get-Module | ForEach-Object Name'
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
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.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.
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.
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
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.
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.
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.
Visual: Import-Module -Force bounces off a locked “Pester.dll” box.
Narration: assemblies stay loaded; switch versions in a new process.
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.
Module 2 · Building a script module: .psm1, Public / Private and module scope
.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- Turn OpsKit v0.1 into a script module:
OpsKit.psm1+Public/*.ps1+Private/*.ps1, imported withImport-Moduleinstead 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'sInModuleScopein Lesson 8). - Reload correctly during development with
Import-Module -Force.
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 live | Your session's scope (global if at the prompt) | The module's own session state |
| Helper functions | Visible to everyone, can be overwritten by accident | Private unless exported |
| Shared variables | Pollute your session ($file leaks) | $script: in module scope, invisible outside |
Get-Command x → Source | empty | OpsKit |
| Unload | Delete each function | Remove-Module OpsKit |
| Versioned, installable | No | Yes, 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
$PSScriptRootis the module folder, wherever it is installed — never use the current location.. $file.FullNameinside the.psm1defines 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.BaseNameexports 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
.psm1callsExport-ModuleMemberat 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 function | Effect |
|---|---|
$x = 1 | Local to that function call |
$script:x = 1 | Module-wide state (cache, connection, settings) — shared by all OpsKit functions, survives between calls, gone on Remove-Module |
$global:x = 1 | Leaks into the user's session — avoid; it is how modules break each other |
.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
What happens inside Import-Module
Step through the import of OpsKit and what the caller can see afterwards.
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
| Command | Purpose | Notes |
|---|---|---|
Import-Module ~/pslab/OpsKit | Import by folder path | Finds OpsKit.psd1 or OpsKit.psm1 in the folder |
Import-Module ./OpsKit.psm1 -Force -PassThru | (Re)load and show the module | Use after every edit |
Export-ModuleMember -Function a, b -Variable v -Alias x | Define the public surface | Only in a .psm1 |
Get-Command -Module OpsKit | What the module exports | Triggers import if needed |
(Get-Module OpsKit).ExportedFunctions | Same, from the module object | |
& (Get-Module OpsKit) { $script:ConfigCache } | Run code inside the module scope | Debugging only; Pester: InModuleScope OpsKit { } |
Remove-Module OpsKit | Unload | Module 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.
New-Item -ItemType Directory ~/pslab/OpsKit/Private -Force, then save Resolve-OpsPath.ps1 and ConvertTo-OpsServer.ps1 from the Commands tab into it.Public/Get-OpsConfig.ps1 and Public/Get-OpsServer.ps1 with the v0.2 versions (cache + helpers).OpsKit.psm1 (Principles tab), then Remove-Item ~/pslab/OpsKit/OpsKit.ps1.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
Get-OpsConfig -Verbose twice — only the first call prints VERBOSE: OpsKit: reading …; -Force reads again.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.
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.
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
Official documentation
Video storyboard (about 90 seconds)
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.
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.
Visual: a $script:ConfigCache jar inside the box, filled once and reused.
Narration: module scope is shared state that callers can't touch.
Visual: an edited file with an old copy still running; -Force swaps it.
Narration: after an edit, import with -Force.
Module 3 · Manifests: New-ModuleManifest, exports, RequiredModules and versions
.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- Generate
OpsKit.psd1withNew-ModuleManifestand explainRootModule,ModuleVersion,GUID,FunctionsToExport,CmdletsToExport/VariablesToExport/AliasesToExport,RequiredModules,PowerShellVersion,CompatiblePSEditionsandPrivateData.PSData. - Explain why explicit export lists, never
'*'— verified: withFunctionsToExport = '*'and dot-sourced files, auto-loading cannot find the commands at all. - Validate with
Test-ModuleManifest, bump versions withUpdate-PSModuleManifest, and read the six typical manifest errors.
What: the keys that matter
| Key | Meaning | OpsKit v0.2 |
|---|---|---|
RootModule | The file to load (.psm1, .dll); decides ModuleType | 'OpsKit.psm1' |
ModuleVersion | A [version] (2–4 numeric parts). Prerelease labels go in PrivateData.PSData.Prerelease | '0.2.0' |
GUID | Identity; generate once, never change | fixed GUID |
FunctionsToExport | Exact list of public functions; also read by auto-loading and the gallery | three names |
CmdletsToExport, VariablesToExport, AliasesToExport | Same for cmdlets, variables, aliases. @() = none | @() |
RequiredModules | Modules that must be present (imported first). Hashtables with ModuleName + ModuleVersion / RequiredVersion / MaximumVersion | none yet |
PowerShellVersion | Minimum engine version; enforced by 5.1 and 7.x | '7.4' |
CompatiblePSEditions | Core and/or Desktop; metadata + gallery filter | 'Core' |
NestedModules, ScriptsToProcess, TypesToProcess, FormatsToProcess | Extra modules, scripts run in the caller's scope at import, .ps1xml files | not used |
PrivateData.PSData | Gallery metadata: Tags, ProjectUri, LicenseUri, ReleaseNotes, Prerelease | tags, 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
| Change | Bump | OpsKit example |
|---|---|---|
| Breaking: rename/remove a command or parameter, change output type | major (1.x → 2.0.0) | Renaming -Environment to -Env |
| New command or parameter, backward compatible | minor (0.2 → 0.3.0) | Invoke-OpsBackup in Lesson 5 |
| Bug fix only | patch (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
| Mechanism | Use when |
|---|---|
RequiredModules in the manifest | Your module needs another module; PowerShell imports it first, and PSResourceGet installs it as a dependency |
#Requires -Modules in a script | A script (not a module) needs modules |
Import-Module inside the .psm1 | Optional/conditional dependencies only — invisible to installers |
$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
Manifest processing pipeline
Command table
| Command | Purpose | Notes |
|---|---|---|
New-ModuleManifest -Path X.psd1 @params | Create a manifest with comments for every key | Generates a GUID if you omit it |
Test-ModuleManifest X.psd1 | Validate syntax, types, referenced files | Does not import the module |
Update-PSModuleManifest X.psd1 -ModuleVersion 0.2.1 | Change keys in place (PSResourceGet) | Keeps other keys |
Import-PowerShellDataFile X.psd1 | Read it as a hashtable | Good for scripts and tests |
(Get-Module X -ListAvailable).ExportedFunctions | What discovery sees | Empty 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.
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
~/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.~/pslab/tmp/bad/OpsKit, reproduce errors 1, 2, 4 and 6 from the Commands tab and write down which ones Test-ModuleManifest catches.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
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).
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
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)
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.
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.
Visual: six red error cards flip over, two of them pass Test-ModuleManifest.
Narration: validation catches syntax, not intent.
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.
Module 4 · PSResourceGet: find, install, update and save; version ranges and trust
*-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- Use
Find-PSResource,Install-PSResource,Save-PSResource,Update-PSResource,Uninstall-PSResourceandGet-InstalledPSResource, and know their aliases (fdres,isres,svres…). - Write NuGet version ranges (
[5.0,6.0),[5.7.1, ], exact5.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.
What: one module, three generations of package management
| PackageManagement (OneGet) + PowerShellGet v2 | PSResourceGet (formerly “PowerShellGet v3”) | |
|---|---|---|
| Commands | Find-Module, Install-Module, Update-Module, Save-Module, Publish-Module, Register-PSRepository | Find-, Install-, Update-, Save-, Publish-, Compress-PSResource, Register-PSResourceRepository |
| Implementation | Script module on top of PackageManagement and a NuGet provider | One binary module (C#), no provider bootstrap |
| Version syntax | -RequiredVersion, -MinimumVersion, -MaximumVersion | -Version with NuGet ranges |
| Bundled with | Windows PowerShell 5.1 (1.0.0.1) and pwsh 7.6 (2.2.5) for compatibility | pwsh 7.4+ (7.6: 1.2.1); installable on 5.1 |
| Status | Maintenance only | Active development (1.3 previews) |
Why: version ranges and scopes
-Version | Meaning | Pester on 2026-11-24 |
|---|---|---|
5.9.1 | Exactly this version | 5.9.1 |
5.7 | Exactly 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.0 | 55 versions |
* | Any (with Find: list all) | 82 stable versions |
| Where it goes | Windows (pwsh 7) | Linux/macOS | Needs admin |
|---|---|---|---|
-Scope CurrentUser (default) | $HOME\Documents\PowerShell\Modules | ~/.local/share/powershell/Modules | No |
-Scope AllUsers | $env:ProgramFiles\PowerShell\Modules | /usr/local/share/powershell/Modules | Yes |
Save-PSResource -Path X | Any 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-PSResourcemanage them. - Save for builds, containers, air-gapped servers and labs: download exact versions into a folder you control, prepend it to
$env:PSModulePathfor that process only. Add-IncludeXmlsoGet-InstalledPSResource -Pathrecognises them (verified: without it they are invisible to that cmdlet). Update-PSResourceinstalls the newer version side by side; it does not remove the old one and does not reload your session.
-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
From -Version to a folder on disk
Command table
| PSResourceGet | PowerShellGet v2 equivalent | Notes |
|---|---|---|
Find-PSResource -Name X [-Version r] [-Prerelease] | Find-Module | Also -Tag, -Type Module|Script, -IncludeDependencies |
Install-PSResource X -Version r -Scope CurrentUser | Install-Module | -TrustRepository, -Reinstall, -AcceptLicense, -AuthenticodeCheck, -PassThru |
Save-PSResource X -Path dir [-IncludeXml | -AsNupkg] | Save-Module | No scope, nothing registered |
Update-PSResource X | Update-Module | Side by side |
Get-InstalledPSResource [X] [-Path dir] | Get-InstalledModule | Only sees packages with PSGetModuleInfo.xml |
Uninstall-PSResource X -Version v | Uninstall-Module | |
Get-PSResourceRepository, Set-PSResourceRepository | Get-PSRepository, Set-PSRepository | Stored 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.
Find-PSResource Pester -Version '[5.0,]' and Find-PSResource PSScriptAnalyzer. Write down the newest 5.x and 6.x of Pester.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
$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
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.~/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).
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
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
No verified video on PSResourceGet 1.2 was found (searches on 2026-11-24 returned only articles); use the documentation below.
Official documentation
- Microsoft.PowerShell.PSResourceGet module · Install-PSResource · Save-PSResource · Find-PSResource · about_PSResourceGet
Video storyboard (about 90 seconds)
Visual: Install-Module (old logo) and Install-PSResource side by side.
Narration: PowerShell 7.6 ships both; new work uses PSResourceGet.
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.
Visual: a gate “untrusted” stops a CI robot.
Narration: untrusted repositories prompt — and prompts fail in automation.
Visual: Save-PSResource drops version folders into ~/pslab/modules.
Narration: save exact versions into a folder you control.
Module 5 · Repositories and publishing: local and private feeds, reproducible installs
.nupkg files or a server. Publishing turns your module folder into a package; pinned, file-driven installs make every machine get the same bits- Explain what a .nupkg contains (your files +
.nuspecgenerated from the manifest) and build one withCompress-PSResource. - Register a folder repository with
Register-PSResourceRepository -Uri, publish withPublish-PSResource, find and install a pinned version, and undo all of it. - Make installs reproducible with
Install-PSResource -RequiredResourceFile(.psd1or.json). - Know how private feeds differ: Azure Artifacts and GitHub Packages (NuGet v3, credentials, search limitations), JFrog, ACR, file shares.
What: package, feed, repository registration
| Term | What it is | OpsKit |
|---|---|---|
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 |
| Feed | Where packages live: a folder / SMB share (all PSResourceGet features), a NuGet v2 server, or a NuGet v3 service | ~/pslab/repo |
| Repository registration | A name + URI + trust + priority in your PSResourceRepository.xml | PSLabLocal (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.
| Feed | URI shape | Auth for install | Notes (PSResourceGet docs) |
|---|---|---|---|
| Folder / file share | C:\repo, \\server\psrepo, /mnt/psrepo | File-system permissions only (no -Credential) | Supports all search scenarios |
| Azure Artifacts | https://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed>/nuget/v3/index.json | Private 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 Packages | https://nuget.pkg.github.com/<owner>/index.json | Always (PAT) | Owner = user or org, not a repository; no wildcard/tag search |
| JFrog Artifactory, MyGet, NuGet.Server, ACR | NuGet v3 / …/nuget / https://<registry>.azurecr.io | Varies | ACR support since 1.1 |
How: publish, then install a pinned version
Publish-PSResource -Path ~/pslab/out/OpsKit -Repository PSLabLocalvalidates the manifest, packs the folder (the whole folder — stage it first) and copies the.nupkgto the feed.Compress-PSResourcedoes only the packing, into any folder — handy when you can't or don't want to register a repository.Install-PSResource OpsKit -Version 0.2.0 -Repository PSLabLocalinstalls exactly that version;RequiredModulesfrom the manifest become NuGet dependencies and are installed too (not for NuGet v3 feeds in 1.2 — install those yourself).- A required-resource file lists name → version range → repository for a whole environment;
Install-PSResource -RequiredResourceFileapplies it.
When: which publishing path
| Situation | Use |
|---|---|
| Laptop, lab, build artifact | Compress-PSResource → .nupkg in a folder |
| Team on Windows with a share | Folder repository on SMB + Publish-PSResource |
| Org with CI/CD | Azure Artifacts / GitHub Packages; publish from the pipeline with a secret, never from a laptop |
| Open source | PowerShell Gallery with an API key (Lesson 8) |
.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
Publish → feed → install → import
*.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
| Command | Purpose | Notes |
|---|---|---|
Compress-PSResource -Path dir -DestinationPath feed | Build Name.Version.nupkg | No repository needed; -PassThru returns the file |
Register-PSResourceRepository -Name N -Uri path -Trusted | Add a feed to your list | Changes user state; undo: Unregister-PSResourceRepository N |
Publish-PSResource -Path dir -Repository N | Pack and push | -ApiKey/-Credential for servers; -NupkgPath to push an existing package |
Find-PSResource -Repository N | Search one feed | Folder feeds support wildcards |
Install-PSResource X -Version 0.2.0 -Repository N | Pinned install | -Version '[0.2.0]' is the same in range syntax |
Install-PSResource -RequiredResourceFile f.psd1 | Install a whole set | .psd1 or .json; also -RequiredResource @{…} |
Save-PSResource X -AsNupkg -Path dir | Mirror packages into a folder feed | Promotion 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.
Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/repo -PassThru.~/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.ps1Module 8 stages a clean copy so this cannot happen.
~/pslab/requirements.psd1 and check it with Import-PowerShellDataFile.PSLabLocal, find and install OpsKit 0.2.0, import it, then uninstall and unregister.~/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.
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
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
No verified video covers PSResourceGet folder repositories or Compress-PSResource.
Official documentation
- Supported repository configurations · Working with local PSRepositories · Publish-PSResource · Compress-PSResource · Register-PSResourceRepository
Video storyboard (about 90 seconds)
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.
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.
Visual: a requirements.psd1 checklist drives three servers to the same versions.
Narration: pinned files make installs reproducible.
Visual: Gallery → review gate → internal feed → servers.
Narration: promote, don't pull straight from the internet.
Module 6 · Providers and drives: FileSystem, Env, Registry, Cert, Variable, Function
Get-ChildItem, Get-Item, New-Item and Get-ItemProperty work on files, environment variables, functions, certificates and the registry — with provider-specific rules- List providers and drives with
Get-PSProvider/Get-PSDrive, and read the capabilities that explain why-Filterworks on files but not onEnv:. - Use
Env:,Variable:,Function:andAlias:with item cmdlets; readCert:andHKLM:/HKCU:(Windows) read-only; distinguish items (keys) from item properties (registry values). - Create a session drive with
New-PSDriveto~/pslab/data, and know why .NET methods cannot see PowerShell drives (Convert-Path).
What: providers and drives
| Provider | Drives | Items are | Item properties | Platform |
|---|---|---|---|---|
| FileSystem | C:, /, Temp: | files, folders | attributes, times (rarely used) | all |
| Environment | Env: | environment variables of this process | — | all |
| Variable | Variable: | PowerShell variables | — | all |
| Function | Function: | functions and filters (including module exports) | — | all |
| Alias | Alias: | aliases | — | all |
| Certificate | Cert: | stores and X.509 certificates | — | Windows |
| Registry | HKLM:, HKCU: | keys | values (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
| Cmdlet | Files | Env: | Registry |
|---|---|---|---|
Get-ChildItem | list folder | list variables | list subkeys |
Get-Item / Test-Path | one file | one variable | one key |
New-Item, Remove-Item, Rename-Item, Copy-Item | ✓ | ✓ (process only) | ✓ (keys) |
Get-Content / Set-Content | file text | value | — |
Get-ItemProperty, Get-ItemPropertyValue, Set-ItemProperty, New-ItemProperty | rare | — | 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) andCredentials; the others onlyShouldProcess.-FilteronEnv:fails; useWhere-Objector 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.
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
Path → provider → item
Command table
| Command | Purpose | Notes |
|---|---|---|
Get-PSProvider | Providers, capabilities, drives | Certificate appears after its module loads |
Get-PSDrive [-PSProvider X] | Drives | FileSystem drives show free space |
New-PSDrive -Name Lab -PSProvider FileSystem -Root ~/pslab/data | Session drive | Remove-PSDrive Lab |
Get-ItemProperty Key -Name V / Get-ItemPropertyValue Key -Name V | Registry values | The second returns the bare value |
Convert-Path X, Resolve-Path X | PowerShell path → provider path | For .NET and native tools |
Test-Path Env:\X, Test-Path Function:\Get-OpsServer | Existence 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.
Get-PSProvider; Get-PSDrive -PSProvider Environment, Variable, Function, Alias.$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.servers.csv through it, then try [IO.File]::ReadAllLines('Lab:\servers.csv') and fix it with Convert-Path.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).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.
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)
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
Official documentation
- about_Providers · about_Environment_Provider · about_Registry_Provider · about_Certificate_Provider · about_Function_Provider · New-PSDrive
Video storyboard (about 90 seconds)
Visual: seven drawers labelled C:, Env:, Variable:, Function:, Alias:, Cert:, HKLM:, one cmdlet opens each.
Narration: providers make every store look like a drive.
Visual: a registry key opens to show values as cards attached to it.
Narration: keys are items, values are item properties.
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.
Visual: -Filter bounces off Env:.
Narration: capabilities differ — Filter is for files.
Module 7 · Cross-platform: paths, case, encodings, line endings and environment variables
.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- 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/$IsMacOSand 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 andSet-Contentwrites the ANSI code page. - Handle CRLF vs LF when splitting text, and split
$env:PATHwith[IO.Path]::PathSeparator.
What: the differences that matter
| Topic | Windows | Linux / macOS | Portable code |
|---|---|---|---|
| Directory separator | \ (also accepts /) | / only | Join-Path; / in literals works on both |
Path list separator (PATH, PSModulePath) | ; | : | [IO.Path]::PathSeparator |
| File-name case | insensitive (NTFS default) | sensitive (Linux), insensitive by default (macOS APFS) | Use the exact case everywhere |
| Env var names | insensitive ($env:path = $env:PATH) | sensitive | Exact case |
Line ending written by Set-Content | CRLF | LF | Split 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 files | attribute | leading dot | -Force |
Aliases like ls, cat, sort | PowerShell aliases | native tools | Full cmdlet names (Lesson 1) |
Why: encodings — what Windows PowerShell 5.1 did
| Writer | pwsh 7.6 | Windows PowerShell 5.1 |
|---|---|---|
Set-Content, Add-Content | UTF-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-File | UTF-8, no BOM | UTF-16 LE with BOM (FF FE) |
-Encoding UTF8 | UTF-8 no BOM (utf8BOM for a BOM) | UTF-8 with BOM |
| Reading a file without BOM | as UTF-8 | as 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
.gitattributessuch as* text=auto eol=lfplus*.ps1 text eol=crlfonly 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).
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
Flowchart: making a path portable
One script, Windows vs Linux
: 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
| Command | Purpose | Notes |
|---|---|---|
Join-Path $a b c | Combine with the right separator | Several child paths (7.x); does not resolve ~ |
Split-Path $p -Parent | -Leaf | -LeafBase | -Extension | Take paths apart | -LeafBase/-Extension are 7.x |
[IO.Path]::Combine(), ::Join() | .NET combining | Combine restarts at a rooted segment |
[IO.Path]::DirectorySeparatorChar, ::PathSeparator | \//, ;/: | |
Convert-Path | Absolute provider path | Before .NET calls |
Format-Hex -Path f | Show bytes | The encoding truth |
-Encoding utf8NoBOM | utf8BOM | unicode | ascii | 1252 | Choose encoding | Code-page numbers accepted in 7.x |
$IsWindows, $IsLinux, $IsMacOS, $PSVersionTable.Platform | Platform checks | Undefined 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.
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.Show-Bytes block from the Commands tab in ~/pslab/tmp.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?`r bug with -split "`n" and fix it with '\r?\n'.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.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.
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))
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
Official documentation
- about_Character_Encoding · Writing portable modules · about_Environment_Variables · Differences from Windows PowerShell 5.1 · about_Windows_PowerShell_Compatibility
Video storyboard (about 90 seconds)
Visual: a backslash path breaks into pieces on a penguin's desk; Join-Path rebuilds it.
Narration: let Join-Path choose the separator.
Visual: the bytes of 'café' in five rows, one row highlighted per encoding.
Narration: the same text, different bytes — Format-Hex tells the truth.
Visual: a line 'web-01' with a hidden ␍ at the end fails an equality check.
Narration: CRLF leaves a carriage return behind.
Visual: SERVERS.CSV found on Windows, not found on Linux.
Narration: Windows forgives case; Linux doesn't.
Module 8 · OpsKit v0.2: a packaged module published to a local repository
Public/, stage a clean copy, package or publish version 0.2.0, then install and import it by version in a clean session- 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-PSResourceorPublish-PSResource. - Install the package into a module folder (as
Install-PSResourcedoes) 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”.
What: OpsKit v0.2
| Path | Role | Ships in the package? |
|---|---|---|
~/pslab/OpsKit/OpsKit.psd1 | Identity: 0.2.0, RootModule, three exports, PowerShell 7.4+, Core | yes |
~/pslab/OpsKit/OpsKit.psm1 | Loader: module state, dot-source Private + Public, export | yes |
Public/Get-OpsConfig.ps1, Get-OpsServer.ps1, Test-OpsEndpoint.ps1 | The API | yes |
Private/Resolve-OpsPath.ps1, ConvertTo-OpsServer.ps1 | Helpers | yes (not exported) |
~/pslab/scripts/Publish-OpsKit.ps1 | Release script | no |
~/pslab/out/OpsKit/ | Staged copy that gets packed | is the package |
~/pslab/repo/OpsKit.0.2.0.nupkg | The 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
.nupkginto~/pslab/modules/OpsKit/0.2.0/and remove the NuGet bookkeeping — the same layout an install produces — then put~/pslab/moduleson PSModulePath for the session. - Consumers pin:
Import-Module OpsKit -RequiredVersion 0.2.0in scripts,#Requires -Modules @{ ModuleName = 'OpsKit'; RequiredVersion = '0.2.0' }, orRequiredModulesin their own manifest.
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
Release pipeline: which run passes?
Below the animation is the interactive troubleshooting tree for module loading problems.
Interactive troubleshooting tree: my module or command doesn't load
Command table
| Command | Purpose | Notes |
|---|---|---|
./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose | Validate, stage, pack into ~/pslab/repo | No registration needed |
./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal | Same, publish to a registered feed | Optional |
Expand-Archive pkg.nupkg -DestinationPath Modules/OpsKit/0.2.0 | Install layout by hand | Then delete _rels, package, [Content_Types].xml, *.nuspec |
Import-Module OpsKit -RequiredVersion 0.2.0 | Exact version | Fails if absent |
Get-Module OpsKit -ListAvailable | What 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.
~/pslab/scripts/Publish-OpsKit.ps1 (Principles tab). If Module 5 left ~/pslab/repo/OpsKit.0.2.0.nupkg behind, delete it first../scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose; run it a second time and read the refusal.Public/Get-OpsHealth.ps1, watch the script stop, remove the file.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
PSLabLocal and run ./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal after bumping to 0.2.1 with Update-PSModuleManifest; undo with Unregister-PSResourceRepository PSLabLocal.~/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.
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' }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
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)
Visual: five gates in a row (manifest, exports, stage, version, pack); a package rolls through.
Narration: a release is a sequence of checks.
Visual: a second 0.2.0 package bounces off the shelf.
Narration: never overwrite a version.
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.
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.
Command cheat sheet
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 call2. 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
~/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 codesScenario
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.
~/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).
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
./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.
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
| Topic | Verified result | Sources (accessed 2026-11-24) |
|---|---|---|
| Bundled package tools | pwsh 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.6 | This lesson's runs; What's New in PowerShell 7.6 |
| Module discovery | PSModulePath 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.1 | about_Modules; about_PSModulePath; about_Requires; runs |
| Script modules | Without Export-ModuleMember: functions exported, variables and aliases not; module scope state; -Force reload | Export-ModuleMember; PowerShell 101: Script modules; runs |
| Manifests | New-ModuleManifest output; wildcard FunctionsToExport hides dot-sourced functions from discovery; six error messages; 5.1 blocked by PowerShellVersion, not by CompatiblePSEditions | about_Module_Manifests; New-ModuleManifest; Test-ModuleManifest; runs |
| PSResourceGet | NuGet 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.2 | Install-PSResource (version syntax, required-resource formats, scopes); Save-PSResource; about_PSResourceGet; runs |
| Repositories | Folder, 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 repository | Supported repository configurations; Working with local PSRepositories; Publish-PSResource; Compress-PSResource |
| Providers | Provider 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-platform | Byte-level encodings in 7.6 and 5.1 (lab machine ACP 65001), CRLF splitting, ~ in .NET calls, case-insensitive Windows lookup | about_Character_Encoding; Writing portable modules; runs |
| OpsKit v0.2 | Publish-OpsKit.ps1 and Test-OpsKitPackage.ps1 run on 7.6.10; package 6.3 KB, 7 module files; all 8 acceptance checks pass | Actual 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):
- PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training (Modules 1, 4)
- PowerShell 7 Overview — John Savill's Technical Training (Modules 1, 7)
- PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training (Modules 2, 3)
- PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training (Module 2)
- PowerShell Master Class - Automation — John Savill's Technical Training (Modules 5, 8)
- New PowerShell Secrets Management Module - Easily use any secret provider — John Savill's Technical Training (Module 5)
- PowerShell Master Class - Data and Objects — John Savill's Technical Training (Module 6)
- Getting Ready for DevOps with PowerShell and VS Code — John Savill's Technical Training (Modules 7, 8)
- PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson (Module 6)
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/USERPROFILEpointed at a scratch folder (so~/pslabwas isolated) and whosePSModulePathstarted from the Windows default machine value; paths were replaced withC:\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-PSResourceto 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 redirectedLOCALAPPDATA), so these could not be isolated; their outputs are labeled “Expected”. The package itself was verified withCompress-PSResourceand 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-Contentencoding result depends on the system ANSI code page; the lab machine uses 65001 (UTF-8), so the 1252 behavior is shown with-Encoding 1252in 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.