PowerShell 第 4 课:模块、包、提供程序与跨平台环境

从“三个需要点源加载的零散函数”到“任何人都能安装的带版本模块”:PowerShell 如何查找并加载模块,如何构建带私有辅助函数和模块级状态的脚本模块,模块清单到底控制什么,PSResourceGet 如何安装和发布包,提供程序如何把注册表和环境变量变成驱动器,以及同一个脚本在 Windows 和 Linux 上运行时会在哪里出问题
PowerShell 7.6 LTS (7.6.10)PSResourceGet 1.2.1仅本地 · 免费已核实 · 2026-11-24
学习路径中的位置 第 1 课讲解了引擎、对象与管道;第 2 课讲解了语言本身(类型、运算符、集合、流程控制);第 3 课把命令写成了高级函数,并创建了课程项目 OpsKit v0.1:三个函数 —— Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint —— 放在 ~/pslab/OpsKit/Public/*.ps1 中,由点源执行 OpsKit.ps1 加载。它在你的笔记本上能用,但没有版本号,公有与私有代码之间没有边界,别人也无法安装。本课的里程碑是 OpsKit v0.2:一个由 OpsKit.psd1 + OpsKit.psm1 组成、带 Public/ 与 Private/ 目录的脚本模块,版本 0.2.0,打包为 .nupkg,发布到本地目录仓库(~/pslab/repo),并在干净的会话中按版本导入。第 5 课在此基础上加入错误处理和 Invoke-OpsBackup(v0.3);第 8 课完成测试并发布 v1.0。
总体学习目标
  • 说明模块的类型(脚本、二进制、清单),在任何平台上用 -split [IO.Path]::PathSeparator 读取 $env:PSModulePath,并预测自动加载和 Import-Module 会选中哪个版本 —— 包括 Windows 自带 Pester 3.4.0 这个陷阱。
  • 构建脚本模块:一个点源加载 Public/ 与 Private/ 的 .psm1,只导出公有函数,并把状态保存在调用方看不到的模块作用域($script:)中。
  • 用 New-ModuleManifest 编写模块清单:RootModule、ModuleVersion、显式的 FunctionsToExport(以及通配符为何会破坏自动加载)、RequiredModules、PowerShellVersion / CompatiblePSEditions;用 Test-ModuleManifest 验证并读懂它的错误信息。
  • 使用 PSResourceGet(Find-、Install-、Save-、Update-、Get-InstalledPSResource),掌握 NuGet 版本范围、安装范围和仓库信任,并与 PowerShellGet v2(Install-Module)对比。
  • 创建本地目录仓库,打包并发布模块(Compress-PSResource / Publish-PSResource),安装固定版本,用依赖清单文件实现可复现的安装,并了解私有源(Azure Artifacts、GitHub Packages)的区别。
  • 用同一组 *-Item / *-ItemProperty cmdlet 操作提供程序与驱动器 —— FileSystem、Env、Variable、Function、Alias、Certificate 和 Registry —— 并用 New-PSDrive 创建自己的驱动器。
  • 编写跨平台代码:用 Join-Path 代替 \,区分大小写的文件系统,$IsWindows,无 BOM 的 UTF-8 与 Windows PowerShell 5.1 编码的差异(用 Format-Hex 证明),CRLF 与 LF,以及 $env:PATH 分隔符。
  • 交付 OpsKit v0.2:验证、暂存、打包、发布到 ~/pslab/repo,并用验收脚本证明干净的 pwsh 导入的正是 0.2.0 版本,且恰好有三个公有命令。

1 小时时间分配

#时间模块核心内容动画 / 交互实验(~/pslab)
0课前准备检查第 3 课的 OpsKit v0.1(或重新创建),创建 ~/pslab/repo、~/pslab/modules、~/pslab/out;确认 PSResourceGet 1.2.x自检清单OpsKit v0.1 热身运行
100–06模块脚本 / 二进制 / 清单模块;各版本的 $env:PSModulePath;自动加载;Get-Module 与 -ListAvailable;Import-Module -Force -PassThru;#Requires -Modules;模块限定名;Pester 3.4.0 陷阱模块解析器:加载哪个模块、哪个版本?在 ~/pslab/modules 中并存 Pester 3.4 与 6.2
206–13脚本模块OpsKit.psm1;点源加载 Public/ + Private/;Export-ModuleMember;默认导出规则;模块作用域与 $script:;& (Get-Module X) { };InModuleScope 预告Import-Module 内部发生了什么把 OpsKit v0.1 改造为 OpsKit.psm1
313–21模块清单New-ModuleManifest;RootModule;ModuleVersion;不用通配符的 FunctionsToExport;RequiredModules;PowerShellVersion / CompatiblePSEditions;PrivateData.PSData;Test-ModuleManifest清单处理流程编写 OpsKit.psd1 并复现六种清单错误
421–28PSResourceGetFind-/Install-/Save-/Update-/Uninstall-PSResource、Get-InstalledPSResource;安装范围;NuGet 版本范围;信任;与 v2 对比从 -Version 范围到磁盘上的目录把 Pester 和 PSScriptAnalyzer 保存到 ~/pslab/modules
528–35仓库目录仓库;Register-PSResourceRepository;Compress- / Publish-PSResource;.nupkg 结构;固定版本安装;-RequiredResourceFile;Azure Artifacts / GitHub Packages发布 → 包源 → 安装 → 导入在 ~/pslab/repo 中生成 OpsKit.0.2.0.nupkg
635–42提供程序与驱动器Get-PSProvider、Get-PSDrive;Env:、Variable:、Function:、Alias:、Cert:、HKCU:/HKLM:;New-PSDrive;*-Item、*-ItemProperty;提供程序能力;PSPath路径 → 提供程序 → 项一个 Lab: 驱动器,以及只读的注册表/证书查询
742–50跨平台Join-Path/Split-Path/[IO.Path];~ 与 .NET;大小写;$IsWindows;无 BOM 的 UTF-8 与 5.1 对比;-Encoding;Format-Hex;CRLF/LF;$env:PATH;仅限 Windows 的 cmdlet同一脚本,Windows 与 Linux 对比7.6 与 5.1 的字节级编码对比
850–60OpsKit v0.2最终目录结构;Publish-OpsKit.ps1(验证 → 暂存 → 打包/发布);安装目录结构;按版本导入;发布规则发布流水线 + 排错树发布 0.2.0 并按版本导入
—课后速查表 · 综合实验Test-OpsKitPackage.ps1:像安装那样解开包,在干净的子 pwsh 中按版本导入,验证导出、私有性、版本和行为结业测验(12 题)八项验收检查全部通过;退出码 0

知识覆盖矩阵

目标技能M1M2M3M4M5M6M7M8关键命令实验
查找并加载模块;预测版本✓·✓✓···✓$env:PSModulePath、Get-Module -ListAvailable、Import-Module -RequiredVersionM1、M8
构建带私有代码的脚本模块·✓✓··✓·✓.psm1、Export-ModuleMember、$script:M2
编写并验证模块清单··✓·✓··✓New-ModuleManifest、Test-ModuleManifest、Update-PSModuleManifestM3、M8
安装、保存和更新包✓··✓✓···Find-PSResource、Save-PSResource、Install-PSResource -Version '[x,y)'M4
发布到仓库;可复现的安装··✓✓✓··✓Register-PSResourceRepository、Publish-PSResource、-RequiredResourceFileM5、综合实验
浏览提供程序与驱动器·✓···✓✓·Get-PSProvider、New-PSDrive、Get-ItemPropertyM6
编写可移植的路径、编码与换行符处理✓····✓✓✓Join-Path、$IsWindows、-Encoding utf8BOM、Format-HexM7
发布带版本的模块并证明其可用·✓✓·✓··✓Compress-PSResource、干净的 pwsh -NoProfile、验收检查M8、综合实验

本课不涵盖的内容(以及在哪里学)

主题为何不在本课在哪里学
高级函数、参数验证、管道输入、函数的作用域规则属于前置知识;本课打包的是你已经写好的函数第 3 课:函数、作用域与高级函数
try/catch、终止性错误、-WhatIf/SupportsShouldProcess、日志错误处理是 OpsKit 的下一层(v0.3)第 5 课
用 C# 编写二进制模块、基于类的模块、DSC 资源需要 .NET 开发能力;运维团队很少编写Microsoft Learn:“Writing a Windows PowerShell module”
把模块远程用于多台机器、Import-Module -PSSession属于多机管理第 6 课
SecretManagement 保管库、CI 中访问私有源的凭据本课只做概览;机密是第 7 课的主题第 7 课
Pester 测试(InModuleScope)、PSScriptAnalyzer、代码签名、CI 发布流水线属于质量与发布第 8 课

如何使用本教材

每个模块 10 个分页
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。先读“原理”和“动画”,再在 ~/pslab 中完成“实验”。模块 2、3、5、8 逐步构建 OpsKit v0.2 —— 请按顺序完成。
学习进度
测验得分 ≥ 70%,或点击“标记本模块为已完成”,都会计入进度。进度保存在本浏览器的本地存储中(如果浏览器禁用本地存储,刷新后会重置)。
语音讲解
“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿。没有语音包时仍可直接阅读讲解稿,或交给 TTS 工具。
版本说明 2026-11-24 在 PowerShell 7.6.10(.NET 10.0.15,Windows)上核实,随附 Microsoft.PowerShell.PSResourceGet 1.2.1、PowerShellGet 2.2.5 和 PackageManagement 1.4.8.1。PowerShell 7.4 与 7.5 已于 2026-11-10 结束支持。核实当天 PowerShell Gallery 上最新的 Pester 是 6.2.0(5.x 的最新版是 5.9.1);Windows 仍在 C:\Program Files\WindowsPowerShell\Modules 中自带 Pester 3.4.0。PSResourceGet 1.3.0 预览版新增了第二个默认仓库(Microsoft Artifact Registry)、感知平台的安装以及 $PSUserContentPath 支持;它们不在 7.6 随附的 1.2.1 中,本课仅作提及。本课的安全规则:除非你主动选择,否则不会向真实的 CurrentUser/AllUsers 范围安装任何东西 —— 实验使用 Save-PSResource -Path ~/pslab/modules 和 ~/pslab/repo 中的目录包源。

模块 0 · 准备:本地包仓库目录

确认第 3 课的 OpsKit v0.1 位于 ~/pslab/OpsKit(或按下文重新创建),创建本课要发布到的目录,并确认你拥有哪个版本的 PSResourceGet
课前 ≈ 10 分钟本地运行 · 免费只写入 ~/pslab
前置知识
  • 第 1–3 课或同等水平:能用 [CmdletBinding()] 和 param() 编写高级函数,并知道点源执行的作用。
  • PowerShell 7.6,以及来自第 1 课模块 0的 ~/pslab/data 数据集(随时可用 ./New-LabData.ps1 重建)。
  • 模块 1 和模块 4 需要访问 www.powershellgallery.com(只读搜索,以及下载到 ~/pslab/modules)。其余内容均可离线完成。

热身:凭记忆回答(30 秒)

1. 对一个只定义函数的文件,& ./OpsKit.ps1 和 . ./OpsKit.ps1 有什么区别?

调用运算符在子作用域中运行它,脚本结束后函数随之消失;点源执行在你的作用域中运行它,函数会保留下来。这就是 OpsKit v0.1 必须点源加载的原因 —— 也是它定义的一切(包括辅助变量)都会落入你会话的原因。

2. 哪个特性让 Test-OpsEndpoint 能通过 IP 属性从管道接收服务器对象?

-ComputerName 上的 [Parameter(ValueFromPipelineByPropertyName)] 加上 [Alias('IP')]:参数绑定器把属性名 IP 与别名匹配(第 1 课模块 5)。

3. 为什么 Get-OpsConfig 用 Import-PowerShellDataFile,而不是点源执行 .psd1?

数据文件以受限语言模式解析:只允许哈希表、数组、字符串和数字,不执行命令。模块清单(.psd1)也是这样读取的 —— 在模块 3 中请记住这一点。

第 1 步:检查 OpsKit v0.1(或重新创建)

如果你完成了第 3 课,就已经有这四个文件;否则现在创建它们 —— 它们是本课起点的最小 v0.1。函数名和参数与第 3 课一致,函数体刻意写得很短。

# ~/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

注意空着的 Source 和 Version 列:点源加载的函数不属于任何模块。没人能问“你用的是哪个 OpsKit?”,没人能安装它,Get-Command -Module OpsKit 也什么都找不到。解决的正是这个问题。

第 2 步:创建本课的目录

'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     # 保留一份 v0.1 副本
Get-ChildItem ~/pslab -Directory -Name
data
modules
OpsKit
out
repo
scripts
tmp
目录在本课中的用途
~/pslab/repo/目录仓库(磁盘上的 NuGet 包源):PSResourceGet 可以查找并安装其中的 .nupkg 文件。在公司里,它会是一个文件共享或 Azure Artifacts / GitHub Packages 包源。
~/pslab/modules/存放 Save-PSResource 下载内容的私有模块目录。我们只在当前会话中把它加入 $env:PSModulePath,因此不会为你的用户安装任何东西。
~/pslab/out/构建输出:被打包的模块的干净副本(没有笔记、测试和 .git)。

第 3 步:你有哪个包管理器?

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 同时随附 PSResourceGet 1.2.1(*-PSResource cmdlet)和旧的 PowerShellGet 2.2.5(Install-Module)。1.0.0.1 的副本来自 Windows PowerShell 5.1 的目录。Get-PSResourceRepository 只读取本地应用数据目录中的 PSResourceRepository.xml,不做任何修改。IsAllowedByPolicy 表示管理员的仓库允许列表(组策略)是否允许该仓库。

环境自检清单

风险与清理 实验只写入 ~/pslab 之下。本课有三个命令会改变用户状态,出现时都标注为“可选”:Register-PSResourceRepository(在你的仓库列表中添加一项)、Install-PSResource / Update-PSResource(安装到你的 CurrentUser 模块目录)以及 Set-PSResourceRepository。每个命令旁边都给出了撤销命令(Unregister-PSResourceRepository、Uninstall-PSResource)。本课的完整清理:Remove-Item ~/pslab/repo, ~/pslab/modules, ~/pslab/out -Recurse -Force;如有需要,可从 ~/pslab/tmp/OpsKit-v0.1 恢复 v0.1。

模块 1 · 模块:类型、PSModulePath、自动加载与 #Requires -Modules

00:00 – 06:00 · 模块就是 PowerShell 能按名称找到的一个文件夹。它在哪里查找、哪个版本胜出、何时加载,决定了你的脚本拿到的是 Pester 6.2,还是 Windows 自带的 Pester 3.4
6 分钟Get-Module · Import-Module★★★★★
学习目标
  • 说出三种模块类型——脚本模块(.psm1)、二进制模块(.dll)、清单模块(描述前两者之一的 .psd1),并能在 Get-Module 输出中识别它们。
  • 用 -split [IO.Path]::PathSeparator 读取 $env:PSModulePath,了解 pwsh 7 按版本和平台添加了哪些条目,并知道文件夹名必须与模块名一致。
  • 解释自动加载,区分 Get-Module(已加载)与 Get-Module -ListAvailable(已安装),并会使用 Import-Module -Force -PassThru、-RequiredVersion 和 #Requires -Modules。
  • 避开在 7.6.10 上验证过的两个版本陷阱:Windows 自带的 Pester 3.4.0,以及在同一会话中切换一个加载了 .NET 程序集的模块版本。
前置知识:模块 0;第 1 课模块 2(命令优先级)。重要程度:★★★★★(模块相关的“在我机器上能跑”问题,几乎总是路径或版本问题)

是什么:三种模块

类型根文件包含内容7.6.10 上的示例
脚本模块Name.psm1PowerShell 函数、变量、别名;加载方式是在模块自己的作用域中运行 .psm1PSReadLine 2.4.5(脚本包装 + dll)、Pester、你的 OpsKit
二进制模块Name.dll编译好的 cmdlet(.NET 类)Microsoft.PowerShell.PSResourceGet 1.2.1(RootModule = './Microsoft.PowerShell.PSResourceGet.dll')、Microsoft.PowerShell.ThreadJob
清单模块Name.psd1描述模块的数据文件:版本、根模块/嵌套模块、导出、依赖要求。没有单一的脚本或二进制根模块时,ModuleType 显示 ManifestCimCmdlets、Microsoft.PowerShell.Utility、Microsoft.PowerShell.Archive

几乎所有真实的模块都同时有模块清单和根模块。ModuleType 报告的是根模块的类型:RootModule = 'OpsKit.psm1' 的 OpsKit 导入后显示为 Script。

为什么:模块通过 PSModulePath 按名称查找

Import-Module OpsKit 和自动加载会在 $env:PSModulePath 的每个文件夹中查找一个名为 OpsKit 的子文件夹,其中包含 OpsKit.psd1、OpsKit.psm1 或 OpsKit.dll——可以直接放在里面,也可以放在 OpsKit/0.2.0/ 这样的版本子文件夹中。pwsh 7 在启动时构建这个变量:

#Windows(pwsh 7.6)Linux / macOS用途
1$HOME\Documents\PowerShell\Modules~/.local/share/powershell/ModulesCurrentUser 安装
2$env:ProgramFiles\PowerShell\Modules/usr/local/share/powershell/ModulesAllUsers 安装
3$PSHOME\Modules$PSHOME/Modulespwsh 自带的模块——不要改动
4–5…\WindowsPowerShell\Modules、System32\WindowsPowerShell\v1.0\Modules—Windows PowerShell 5.1 的文件夹,为兼容性追加在后面(Pester 3.4.0 就在这里)

分隔符在 Windows 上是 ;,在 Linux/macOS 上是 :——始终用 [IO.Path]::PathSeparator 拆分。Windows PowerShell 5.1 用 Documents\WindowsPowerShell\Modules 代替第 1 项,所以从 5.1 安装的模块在 pwsh 中会“找不到”(第 1 课模块 1)。

怎么做:自动加载与显式导入

  1. 你输入了一个任何已加载模块都不提供的命令。PowerShell 遍历 PSModulePath 上的模块,读取每个模块清单的导出列表(有缓存),找到导出该名称的模块,导入它,然后执行命令。
  2. 如果安装了多个版本,Import-Module Name 和自动加载会按顺序搜索各条目,并从第一个包含该模块的条目中取最高版本——后面条目中的更新版本会被忽略(已在 7.6.10 上验证:较前文件夹中的 Pester 5.9.1 胜过了较后文件夹中的 6.2.0);用 -RequiredVersion、-MinimumVersion、-MaximumVersion 可以锁定版本。
  3. Get-Module 列出本会话中已加载的模块;Get-Module -ListAvailable 列出 PSModulePath 上已安装的模块(不会导入任何东西)。
  4. 如果 X 已经加载,Import-Module X 什么都不做——-Force 会重新运行它。-PassThru 返回模块对象,让你看清拿到的是什么。
  5. $PSModuleAutoLoadingPreference = 'None' 在会话中关闭自动加载;#Requires -Modules 让脚本在模块(及版本)不可用时拒绝启动。

何时用:模块限定名

Microsoft.PowerShell.Utility\Get-Date 会运行该模块中的命令,即使有同名函数或别名遮蔽它,并且会自动加载该模块。在 7.6 中,线程作业模块改名为 Microsoft.PowerShell.ThreadJob;旧的限定名 ThreadJob\Start-ThreadJob 现在会失败(见下方验证)。限定名很精确——也正因如此,模块一改名就会失效。

常见误区① “Get-Module 显示已安装的模块”——它显示的是已加载的;加上 -ListAvailable。② “Import-Module Pester 会给我最新的 Pester”——在一台原装 Windows 上,它给你的是 Windows PowerShell 文件夹中的 3.4.0,没有任何 Pester 5/6 语法。③ “Import-Module -Force 能切换任何版本”——如果旧版本已经加载了 .NET 程序集就不行;请开一个新会话。④ “模块文件夹复制到哪里都能用”——只有 PSModulePath 上的文件夹才能按名称找到,而且文件夹名必须与模块名一致。⑤ “有了自动加载就不需要导入”——脚本应该用 #Requires -Modules 或显式的 Import-Module 声明依赖。

架构图:从命令名到已加载的模块

Get-OpsServer尚未加载 $env:PSModulePath(按顺序)1 Documents\PowerShell\Modules · 2 Program Files3 $PSHOME\Modules · 4–5 WindowsPowerShell <entry>\OpsKit\0.2.0\OpsKit.psd1文件夹名 = 模块名多个版本文件夹并存 读取模块清单(仅数据)FunctionsToExport 中有这个名称吗?未锁定时取最高版本 导入:运行 OpsKit.psm1在新的模块作用域中导出公有函数 命令执行 · Get-Module 列出 OpsKit · Get-Command 显示 Source = OpsKit,Version = 0.2.0捷径或覆盖:Import-Module -RequiredVersion · #Requires -Modules · Module\Command · $PSModuleAutoLoadingPreference
图 1-1:自动加载读取的是模块清单而不是代码——这就是模块 3 中清单导出列表如此重要的原因

版本选择:同一名称,三个文件夹

~/pslab/modules(置于最前)Pester\6.2.0Pester\5.9.1 $PSHOME\Modules没有 PesterPSResourceGet 1.2.1、PSReadLine 2.4.5 WindowsPowerShell\ModulesPester\3.4.0(Windows 自带)PSReadLine 2.0.0 Import-Module Pester → 6.2.0 (第一个含 Pester 的文件夹中的最高版本) Import-Module Pester -RequiredVersion 5.9.1 → 5.9.1 (6.2.0 的 Pester.dll 已加载时只能在新会话中) 路径中没有 ~/pslab/modules → 3.4.0 (经典陷阱)
图 1-2:由第一个包含该模块的 PSModulePath 文件夹决定,再取其中的最高版本——所以文件夹的顺序决定了行为

模块解析器:加载的是哪个模块、哪个版本?

选择一个场景,逐步查看 PowerShell 检查了什么。所有最终输出都在 7.6.10 上复现过。

就绪。
动画背后的真实机制 命令发现首先检查已加载的命令(第 1 课模块 2)。如果没有匹配且自动加载已开启,PowerShell 会借助按用户保存的模块分析缓存(记录各模块导出的名称)枚举 PSModulePath 上的模块,导入第一个导出该名称的模块,然后重试。#Requires -Modules 在脚本第一行执行之前就会被评估;模块加载的 .NET 程序集会一直留在进程中,直到进程退出。

命令表

命令用途说明
$env:PSModulePath -split [IO.Path]::PathSeparator模块的搜索位置可移植的拆分(; / :)
Get-Module已加载的模块仅限当前会话
Get-Module Name -ListAvailable已安装的模块,所有版本不会导入
Import-Module Name -PassThru导入并返回模块对象查看 Version、ModuleBase
Import-Module Name -Force重新运行模块修改模块后使用;无法卸载程序集
Import-Module Name -RequiredVersion 5.9.1精确版本另有 -MinimumVersion、-MaximumVersion
Remove-Module Name从会话中卸载命令程序集仍保持加载
#Requires -Modules @{ ModuleName='X'; ModuleVersion='5.0.0' }脚本前置要求ModuleVersion = 最低版本;RequiredVersion = 精确版本
Module\Command模块限定调用绕过遮蔽;会自动加载
$PSModuleAutoLoadingPreferenceAll(默认)、ModuleQualified、None用于诊断;生产中很少使用
$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

第 4、5 项来自 Windows PowerShell 使用的机器级变量;pwsh 在前面加上自己的三项。如果你的输出有重复项,说明有人把 pwsh 的路径写进了机器级变量——无害,但容易混淆。

Get-Module | Format-Table Name, ModuleType, Version
$null = Get-PSResourceRepository            # 来自尚未加载模块的命令
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

如何验证:这个二进制模块在它的命令运行之后才出现——这就是自动加载。常见错误:根据普通的 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# 是找到该模块的 PSModulePath 条目序号。PSReadLine 安装了两份;pwsh 加载 2.4.5,因为 $PSHOME\Modules 排在前面。Pester 只有 Windows PowerShell 文件夹中的 3.4.0。

# Pester 陷阱,然后是修复:在你掌控的文件夹中放一个更新的 Pester
Import-Module Pester
(Get-Module Pester).Version.ToString()
@(Get-Command Should-Be -ErrorAction SilentlyContinue).Count
./scripts/needs-pester.ps1          # 第一行是:#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'..
# (模块 4 已将 Pester 5.9.1 和 6.2.0 保存到 ~/pslab/modules 之后)—— 新会话:
$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
# ……然后在同一会话中试图切回 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

如何验证:之后 (Get-Module Pester).Version 仍然是 6.2.0。常见错误:以为 -Force 能切换版本。生产用法:按进程锁定版本——CI 作业启动一个全新的 pwsh,并用 -RequiredVersion 导入(或使用带 RequiredVersion 的 #Requires)。

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.

目标:亲眼看到自动加载、Pester 陷阱和 #Requires 的效果。环境:Windows 上的 pwsh 7.6(Linux/macOS 上没有 Pester 3.4——你只会看到“没有 Pester”)。安全性:只读,外加 ~/pslab/scripts 中的一个小脚本。成本:无。

列出搜索路径,并按根路径统计已安装模块数:
$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

计数取决于你安装了什么;在实验机上,大部分模块位于 Windows PowerShell 文件夹(Az 是为 5.1 安装的)。

观察自动加载(在一个干净的子进程中):
pwsh -NoProfile -Command 'Get-Module | ForEach-Object Name; "--"; $null = Get-PSResourceRepository; Get-Module | ForEach-Object Name'
复现 Pester 陷阱:创建脚本并运行。
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,然后定义 function Get-Date { 'shadowed' },分别调用两种形式。用 Remove-Item Function:\Get-Date 删除该函数。
清理:无需清理——保留 needs-pester.ps1;模块 4 会让它通过。

案例 1:CI 运行了错误的测试框架

问题:流水线中的一个步骤在自托管 Windows 代理上运行 Invoke-Pester;为 Pester 5 编写的测试以奇怪的语法错误失败,尽管“Pester 已安装”。根本原因:代理上只有 Windows 自带的 Pester 3.4.0,自动加载选中了它。修复:把所需的 Pester 保存到构建本地文件夹(Save-PSResource -Path ./modules),在作业中把它加到 $env:PSModulePath 最前面,并执行 Import-Module Pester -RequiredVersion …;在测试入口脚本中加上 #Requires -Modules。教训:没有版本的“已安装”毫无意义。

案例 2:长期运行的自动化主机卡在旧模块上

问题:一个 Runbook 工作进程更新了模块,但作业仍按旧行为失败,即使执行了 Import-Module -Force。根本原因:该模块带有 .NET 程序集;第一个版本的程序集一直留在工作进程中。修复:更新后在全新进程中运行作业(或回收工作进程);在作业中锁定版本。上文已用 Pester 6.2.0 → 5.9.1 复现。

案例 3:模块改名导致限定调用失效

问题:脚本迁移到 7.6 后,ThreadJob\Start-ThreadJob 失败,而 Start-ThreadJob 正常。根本原因:模块现在叫 Microsoft.PowerShell.ThreadJob。修复:更新限定名;只在确实存在遮蔽风险的地方使用限定名。

常见错误与修复

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

原因:PSModulePath 上没有名为 X 的文件夹、名称拼错,或者模块是为另一个版本的 PowerShell 安装的。

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

修复:按路径导入,或把模块放到 PSModulePath 上一个与模块同名的文件夹中。

测试因旧语法失败 / 找不到 Should-Be,尽管 Pester 已安装

原因:加载的是 Pester 3.4.0(Windows 自带)。

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

修复:在 PSModulePath 上提供 Pester 6.x(或 5.x),并用 -RequiredVersion 或 -MinimumVersion 导入。

Assembly with same name is already loaded

原因:进程中已经有该模块另一个版本的 dll。

修复:启动一个新的 pwsh;先导入你需要的版本。

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

原因:PSModulePath 上没有该模块或所需的最低版本。脚本根本没有启动——什么都没执行。

修复:安装/保存该版本,或有意识地放宽要求。

命令行练习
1. 显示 PSReadLine 的每个已安装版本及其所在文件夹。
Get-Module PSReadLine -ListAvailable | Format-Table Name, Version, ModuleBase
2. 写一个脚本头,除非恰好有 Pester 5.9.1 可用,否则拒绝运行。
#Requires -Modules @{ ModuleName = 'Pester'; RequiredVersion = '5.9.1' }

ModuleVersion 表示“至少”;RequiredVersion 表示“恰好”;另外还有 MaximumVersion。

场景分析
同事说:“Get-Module 里没有 Az 模块,所以 Az 没装——我要为所有用户再装一遍。”你首先检查什么?

Get-Module 只列出已加载的模块。检查 Get-Module Az.Accounts -ListAvailable 和 PSModulePath 条目;Az 可能是为 Windows PowerShell 5.1 安装的(pwsh 通过第 4–5 项也能看到),或者装在另一个用户下。为 AllUsers 重新安装会产生第二份副本,带来新的“哪个版本胜出”问题。确定一个安装范围和一个版本,并在脚本中锁定。

已核实的教学视频

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
英语 · 基础知识,包括查找和使用模块(标题与频道已核实)
▶
PowerShell 7 Overview — John Savill's Technical Training
英语 · PowerShell 7 与 Windows PowerShell 对比、并行安装(标题与频道已核实)

没有找到讲解 Pester 3.4 陷阱或程序集重新加载的已核实视频;请使用本模块的复现示例。

官方文档

视频分镜(约 90 秒)

本教材无法直接生成视频或 MP3;分镜和讲解稿可交给视频工具使用。

镜头 1 · 0–20 秒
画面:一个命令名落入标着 PSModulePath 的漏斗;五个文件夹依次亮起。
讲解:模块就是按名称、按 PSModulePath 顺序找到的文件夹。
镜头 2 · 20–45 秒
画面:三个 Pester 文件夹(6.2.0、5.9.1、3.4.0);把第一个文件夹从路径中移除,3.4.0 胜出。
讲解:路径上的最高版本胜出——而 Windows 自带 Pester 3.4。
镜头 3 · 45–70 秒
画面:Import-Module -Force 撞在一个上锁的“Pester.dll”盒子上被弹回。
讲解:程序集会一直保持加载;在新进程中切换版本。
镜头 4 · 70–90 秒
画面:一个带 #Requires 行的脚本在门口被红色标志拦下。
讲解:声明你需要什么;在第一行之前失败,而不是运行到一半。
或测验得分 ≥ 70%

模块 2 · 构建脚本模块:.psm1、Public / Private 与模块作用域

06:00 – 13:00 · 一个 .psm1:为每个函数点源加载一个文件,只导出公有函数,并把共享状态保存在调用方无法触及的模块作用域中
7 分钟OpsKit.psm1★★★★★
学习目标
  • 把 OpsKit v0.1 改造为脚本模块:OpsKit.psm1 + Public/*.ps1 + Private/*.ps1,用 Import-Module 导入,而不再点源执行。
  • 用 Export-ModuleMember 控制公开接口,并了解不使用它时的默认行为(已验证:所有函数都会导出,变量和别名不会)。
  • 使用模块作用域:模块中的 $script: 变量由其所有函数共享,对调用方不可见;可用 & (Get-Module OpsKit) { … } 窥视内部(第 8 课介绍 Pester 的 InModuleScope)。
  • 开发过程中用 Import-Module -Force 正确地重新加载。
前置知识:模块 1;第 3 课(高级函数、作用域)。重要程度:★★★★★

是什么:脚本模块就是在自己作用域中运行的 .psm1

导入 OpsKit.psm1 时,PowerShell 会创建一个模块会话状态 —— 专属于该模块的私有作用域树 —— 并在其中运行这个文件。文件定义的一切都位于该作用域中。随后模块把其中一部分导出到调用方的会话。函数被调用时仍在模块作用域中运行,因此能看到模块的 $script: 变量和私有辅助函数。

v0.1:. ./OpsKit.ps1(点源执行)v0.2:Import-Module OpsKit
函数位于哪里你会话的作用域(在提示符下则为全局)模块自己的会话状态
辅助函数所有人可见,可能被意外覆盖除非导出,否则私有
共享变量污染你的会话($file 会泄漏)模块作用域中的 $script:,外部不可见
Get-Command x → Source空OpsKit
卸载逐个删除函数Remove-Module OpsKit
带版本、可安装否是,有了模块清单之后(模块 3)

为什么:每个函数一个文件,Public / Private

这是大多数开源模块采用的常见布局:Public/ 中每个导出命令一个文件(文件名 = 函数名),Private/ 存放辅助函数,.psm1 只是一个简短的加载器。评审和合并只涉及一个小文件;加载器可以从文件名推导出导出列表。代价是:导入时点源加载许多文件,比一个大 .psm1 稍慢 —— 第 8 课会展示如何在构建步骤中把它们合并后再发布。

怎么做:加载器

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

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

# Only the public functions leave the module. The manifest (OpsKit.psd1) repeats this list.
Export-ModuleMember -Function $public.BaseName
  • $PSScriptRoot 是模块目录,无论模块安装在哪里 —— 永远不要依赖当前位置。
  • 在 .psm1 内执行 . $file.FullName,会把函数定义在模块作用域中;这就是为什么点源执行在这里是正确的,而在不依赖配置文件的脚本中是错误的。
  • 先加载 Private 文件,这样公有函数在导入时如有需要就能使用它们。
  • Export-ModuleMember -Function $public.BaseName 按文件名导出 —— 函数名与文件名不同的函数会悄无声息地保持私有(评审规则:文件名 = 函数名)。
  • 只要 .psm1 调用了 Export-ModuleMember,就只导出它列出的内容。不调用时,所有函数都会导出,但变量和别名都不会(见下文验证)。

何时用:模块作用域与全局作用域

在模块函数中写效果
$x = 1仅限本次函数调用的局部变量
$script:x = 1模块级状态(缓存、连接、设置)—— 所有 OpsKit 函数共享,在多次调用间保留,Remove-Module 后消失
$global:x = 1泄漏到用户会话 —— 应避免;模块之间正是这样互相破坏的
常见误区① “.psm1 像点源脚本一样在我的作用域中运行” —— 它在模块自己的会话状态中运行。② “没有 Export-ModuleMember 就什么都不导出” —— 所有函数都会导出(包括辅助函数);变量和别名不会。③ “模块中的 $script: 指调用脚本的作用域” —— 它指模块作用域。④ “改完文件再运行一次命令就行” —— 在 Import-Module -Force 之前旧定义一直生效。⑤ “私有函数是安全边界” —— 它们只是不出现在发现结果中,并未受到保护:& (Get-Module OpsKit) { ConvertTo-OpsServer … } 依然可以调用它们。

架构图:作为脚本模块的 OpsKit v0.2

~/pslab/OpsKit/ OpsKit.psd1 (模块 3)OpsKit.psm1 (加载器) Public/Get-OpsConfig.ps1Get-OpsServer.ps1Test-OpsEndpoint.ps1 Private/ConvertTo-OpsServer.ps1Resolve-OpsPath.ps1 Import-Module 模块会话状态(OpsKit) $script:ConfigCache$script:DefaultConfigPath 公有函数Get-OpsConfig · Get-OpsServerTest-OpsEndpoint 私有辅助函数ConvertTo-OpsServerResolve-OpsPath 导出 你的会话Get-OpsConfigGet-OpsServerTest-OpsEndpoint无辅助函数、无 $script:Source = OpsKit
图 2-1:模块作用域是一个只有一扇门的盒子 —— 门就是导出列表。通过这扇门调用的函数仍在盒子内部运行

Import-Module 内部发生了什么

逐步查看 OpsKit 的导入过程,以及调用方之后能看到什么。

就绪。
动画背后的真实机制 Import-Module 创建一个拥有独立 SessionState 的 PSModuleInfo,在其中运行根模块,收集导出的函数(先经 Export-ModuleMember 过滤,再经模块清单的 *ToExport 列表过滤),然后把它们导入调用方的会话状态。函数会记住定义它的会话状态;调用它时会切换到那个模块作用域。

命令表

命令用途说明
Import-Module ~/pslab/OpsKit按目录路径导入在目录中查找 OpsKit.psd1 或 OpsKit.psm1
Import-Module ./OpsKit.psm1 -Force -PassThru(重新)加载并显示模块每次修改后使用
Export-ModuleMember -Function a, b -Variable v -Alias x定义公开接口只能在 .psm1 中使用
Get-Command -Module OpsKit模块导出了什么必要时会触发导入
(Get-Module OpsKit).ExportedFunctions同上,从模块对象读取
& (Get-Module OpsKit) { $script:ConfigCache }在模块作用域内运行代码仅用于调试;Pester 中为 InModuleScope OpsKit { }
Remove-Module OpsKit卸载模块状态被丢弃

私有辅助函数与两个重构后的公有函数

# ~/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:缓存在模块作用域中)
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:使用私有辅助函数)
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 与 v0.1 相同。OpsKit.ps1(v0.1 的加载器)被删除。

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.

如何验证:Source 现在是 OpsKit;调用方不认识私有辅助函数,但它在 Get-OpsServer 内部能正常工作。Version : 0.0 —— 单独的 .psm1 没有版本;模块 3 会解决这个问题。

"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          # 已缓存:不读取文件
Get-OpsConfig -Verbose -Force | Out-Null   # 强制重新读取
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

只有一行 VERBOSE:Get-OpsServer 早已填充了缓存,所以第一次 Get-OpsConfig 什么也没读。调用方的 $script:ConfigCache 是另一个变量(调用方自己的脚本作用域),所以是空的。

没有 Export-ModuleMember 时的默认行为,以及过时的定义

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

如何验证:辅助函数泄漏了;别名 glp 和变量没有;$script:Counter 在两次调用之间保留了值。最后一行:~/pslab 不在 PSModulePath 中,所以在模块 8 安装它之前请按路径导入。常见错误:依赖默认行为,把每个辅助函数都作为公有命令发布出去。生产用法:始终显式导出 —— 在 .psm1 中,更重要的是在模块清单中。

# 把 TimeoutMs 默认值从 500 改为 750,然后:
Import-Module ~/pslab/OpsKit            # 已加载 → 什么都不发生
(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

目标:把 OpsKit v0.1 改造为一个具备公有/私有边界和模块级状态的脚本模块。环境:pwsh 7.6,模块 0 中的 ~/pslab/OpsKit(备份在 ~/pslab/tmp/OpsKit-v0.1)。成本:无。

创建目录和私有辅助函数:New-Item -ItemType Directory ~/pslab/OpsKit/Private -Force,然后把“命令”分页中的 Resolve-OpsPath.ps1 和 ConvertTo-OpsServer.ps1 保存到其中。
重构两个公有函数:用 v0.2 版本(缓存 + 辅助函数)替换 Public/Get-OpsConfig.ps1 和 Public/Get-OpsServer.ps1。
编写加载器并删除旧加载器:保存 OpsKit.psm1(“原理”分页),然后执行 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 两次 —— 只有第一次打印 VERBOSE: OpsKit: reading …;加 -Force 会重新读取。
清理:Remove-Module OpsKit。保留文件 —— 模块 3 会添加模块清单。

案例 1:变成了 API 的辅助函数

问题:另一个团队的脚本调用了共享模块中的 Format-InternalDate。一次重构给它改了名,他们的夜间作业随之失败。根本原因:模块既没有 Export-ModuleMember,也没有清单导出列表,所以每个辅助函数都是公有的。修复:显式导出;未导出的内容都可以自由修改。把导出列表当作 API 契约并为其管理版本(模块 3)。

案例 2:两个模块争抢同一个全局变量

问题:导入模块 B 改变了模块 A 的行为。根本原因:两者都把设置存放在 $global:Config 中。修复:每个模块内部使用 $script: 状态,并提供 Get-/Set- 函数来读取和修改它。

案例 3:“我的修复不起作用”—— 其实修复从未被加载

问题:一位工程师修改了函数,反复运行命令半小时,看到的仍是旧行为。根本原因:模块早已加载,不带 -Force 的 Import-Module 什么也没做。修复:修改后执行 Import-Module … -Force,或在全新的 pwsh -NoProfile 中测试;VS Code 用户可以每次在新终端中运行模块测试。

常见错误与修复

The term 'Helper' is not recognized …(发生在模块函数内部)

原因:私有文件没有被点源加载(目录名错误、文件因语法错误被跳过),或者辅助函数定义在导入时就要运行的代码之后。

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

原因:某个文件存在解析错误或运行时错误;加载器会带上文件名重新抛出。

修复:打开该文件;[System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$null, [ref]$errors) 可以在不运行的情况下列出语法错误。

函数存在于模块中,但没有被导出

原因:它的文件名与函数名不同,因此 $public.BaseName 中没有它 —— 或者模块清单的 FunctionsToExport 漏掉了它(模块 3)。

修改没有生效

Import-Module -Force,或者开一个新会话。

命令行练习
1. 列出 OpsKit 模块作用域中存在的所有函数,包括私有函数。
& (Get-Module OpsKit) { Get-ChildItem Function: | Where-Object { $_.Module.Name -eq 'OpsKit' } | ForEach-Object Name }
2. 不修改文件,为一次快速实验只导出 Get-OpsServer。
Import-Module ~/pslab/OpsKit/OpsKit.psm1 -Function Get-OpsServer -Force
Get-Command -Module OpsKit

Import-Module -Function 过滤的是导入到你的会话中的内容;它无法增加模块本身没有导出的东西。

场景分析
模块中一个函数设置 $ConnectionString = …,另一个函数读取它;结果“时灵时不灵”。请解释并修复。

普通赋值会在第一个函数的作用域中创建局部变量;只有当第二个函数恰好在第一个函数内部被调用时才能看到它(动态作用域)。模块级状态请用 $script:ConnectionString,更好的做法是把值作为参数传入 / 作为对象返回。

已核实的教学视频

▶
PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training
英文 · 通向模块的高级函数与脚本技巧(标题和频道已核实)
▶
PowerShell Master Class - PowerShell Scripting — John Savill's Technical Training
英文 · 脚本与函数(标题和频道已核实)

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:零散的函数洒进会话;随后同样的文件被收进一个标着 OpsKit 的盒子。
旁白:点源执行把代码倒进你的会话;模块把代码装在自己的盒子里。
镜头 2 · 20–50 秒
画面:Public/ 与 Private/ 目录;只有 Public 中的文件能穿过标着 Export-ModuleMember 的门。
旁白:每个函数一个文件;按名称导出公有函数。
镜头 3 · 50–75 秒
画面:盒子里有一个 $script:ConfigCache 罐子,只装填一次,反复使用。
旁白:模块作用域是调用方碰不到的共享状态。
镜头 4 · 75–90 秒
画面:文件已修改,但旧副本仍在运行;-Force 把它换掉。
旁白:修改之后,用 -Force 重新导入。
或测验得分 ≥ 70%

模块 3 · 模块清单:New-ModuleManifest、导出、RequiredModules 与版本

13:00 – 21:00 · .psd1 是模块的身份证:版本、根模块、导出、依赖要求和仓库元数据。PowerShell 把它当作数据读取 —— 在运行你的任何代码之前
8 分钟OpsKit.psd1★★★★★
学习目标
  • 用 New-ModuleManifest 生成 OpsKit.psd1,并解释 RootModule、ModuleVersion、GUID、FunctionsToExport、CmdletsToExport/VariablesToExport/AliasesToExport、RequiredModules、PowerShellVersion、CompatiblePSEditions 和 PrivateData.PSData。
  • 说明为什么要用显式导出列表,绝不用 '*' —— 已验证:FunctionsToExport = '*' 加上点源加载的文件,自动加载根本找不到这些命令。
  • 用 Test-ModuleManifest 验证,用 Update-PSModuleManifest 升级版本,并读懂六种典型的清单错误。
前置知识:模块 2。重要程度:★★★★★

是什么:重要的键

键含义OpsKit v0.2
RootModule要加载的文件(.psm1、.dll);决定 ModuleType'OpsKit.psm1'
ModuleVersion一个 [version](2–4 个数字段)。预发布标签放在 PrivateData.PSData.Prerelease'0.2.0'
GUID身份标识;只生成一次,永不更改固定 GUID
FunctionsToExport公有函数的确切列表;自动加载和仓库也会读取它三个名称
CmdletsToExport、VariablesToExport、AliasesToExport对应 cmdlet、变量、别名。@() = 不导出@()
RequiredModules必须存在的模块(先行导入)。哈希表包含 ModuleName + ModuleVersion / RequiredVersion / MaximumVersion暂无
PowerShellVersion最低引擎版本;5.1 和 7.x 都会强制检查'7.4'
CompatiblePSEditionsCore 和/或 Desktop;元数据 + 仓库筛选'Core'
NestedModules、ScriptsToProcess、TypesToProcess、FormatsToProcess附加模块、导入时在调用方作用域运行的脚本、.ps1xml 文件未使用
PrivateData.PSData仓库元数据:Tags、ProjectUri、LicenseUri、ReleaseNotes、Prerelease标签、说明

为什么:显式导出(不用通配符)

自动加载、Get-Module -ListAvailable 和 PowerShell Gallery 都是在不运行模块的情况下读取清单。如果 FunctionsToExport 列出了名称,它们立刻就知道有哪些命令。如果是 '*',PowerShell 就得分析 .psm1 去猜 —— 而静态分析看不到点源加载的文件中定义的函数。在 7.6.10 上用 PSModulePath 中的一份 OpsKit 副本验证:

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

使用通配符时,模块对自动加载不可见;在大型模块上,这种分析还会让命令发现变慢。清单的列表和 .psm1 的 Export-ModuleMember 都会过滤:一个函数必须同时通过两者才会被导出。

怎么做:为模块使用语义化版本

变更升级OpsKit 示例
破坏性:重命名/删除命令或参数,改变输出类型主版本(1.x → 2.0.0)把 -Environment 改名为 -Env
新增命令或参数,向后兼容次版本(0.2 → 0.3.0)第 5 课的 Invoke-OpsBackup
仅修复缺陷修订号(0.2.0 → 0.2.1)修复 ~ 展开

1.0 之前任何东西都可能变化(SemVer),但用户仍会固定版本 —— 所以在第 8 课的 v1.0 之前,把次版本升级视为“可能破坏兼容”。已发布的版本不可变:绝不要用不同内容重新发布 0.2.0。

何时用:RequiredModules、#Requires 与 psm1 中的 Import-Module

机制适用场景
清单中的 RequiredModules你的模块需要另一个模块;PowerShell 先导入它,PSResourceGet 把它作为依赖一并安装
脚本中的 #Requires -Modules脚本(而非模块)需要某些模块
.psm1 中的 Import-Module仅用于可选/有条件的依赖 —— 安装程序看不到
常见误区① “清单是脚本” —— 它是受限的数据文件;不能有变量或命令(某些键中的 $PSScriptRoot 等少数例外)。② “FunctionsToExport = '*' 是安全的默认值” —— 它会破坏点源加载型模块的自动加载,并拖慢命令发现。③ “Test-ModuleManifest 通过就意味着模块能导入” —— 已验证:RequiredModules 未满足、漏掉导出时它都通过了。④ “CompatiblePSEditions = 'Core' 能挡住 Windows PowerShell” —— 已验证:5.1 仍尝试加载 OpsKit;真正挡住它的是 PowerShellVersion = '7.4'。⑤ “ModuleVersion = 'v0.2.0' 或 '0.2.0-beta' 可以用” —— 它必须是普通的 [version]。

流程图:Import-Module 如何处理模块清单

OpsKit.psd1作为数据解析 验证键类型、语法 PowerShellVersion版本 / 宿主检查 RequiredModules逐个先行导入 RootModule运行 OpsKit.psm1 导出过滤Export-ModuleMember ∩ FunctionsToExport 你的会话3 个命令,v0.2.0 在哪里失败(均已在 7.6.10 上复现) “not a valid PowerShell module manifest file” → 语法 / RootModule 拼写错误 · “Cannot convert value "v0.2.0" to type System.Version” “requires a minimum PowerShell version of '7.7'” · “The required module 'Pester' is not loaded” 静默:FunctionsToExport 中漏掉的函数就是不会被导出
图 3-1:“RootModule”之前的每一项检查都不运行你的代码 —— 正因如此,安装程序、仓库和自动加载都能读取清单

清单处理流程

就绪。

命令表

命令用途说明
New-ModuleManifest -Path X.psd1 @params创建为每个键都带注释的清单省略 GUID 时会自动生成
Test-ModuleManifest X.psd1验证语法、类型、引用的文件不会导入模块
Update-PSModuleManifest X.psd1 -ModuleVersion 0.2.1原地修改键(PSResourceGet)保留其他键
Import-PowerShellDataFile X.psd1把它读成哈希表适合脚本和测试
(Get-Module X -ListAvailable).ExportedFunctions命令发现看到的内容使用 '*' + 点源加载时为空
$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.'

注意:在 7.6.10 上,New-ModuleManifest 把 VariablesToExport = @() 写成了注释(# VariablesToExport = @())。被注释掉的键会回退到默认值,对变量而言就是“导出 .psm1 所导出的内容”—— 而我们的 Export-ModuleMember 不导出变量,所以结果相同。如果想显式写明,取消该行注释即可。在 Windows 上,该文件以 ASCII/UTF-8 编码、CRLF 换行符写入。

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 描述的是清单本身(类型 Manifest);导入后,模块报告的是其根模块的类型(Script),并且终于有了版本号。

复现六种清单错误

# 每一段都修改 ~/pslab/tmp/bad/OpsKit 中的副本,然后运行 Test-ModuleManifest 和/或 Import-Module
# 1. RootModule = 'OpsKit.pms1'          2. ModuleVersion = 'v0.2.0'      3. 少一个引号
# 4. FunctionsToExport 中没有 Test-OpsEndpoint
# 5. RequiredModules = @(@{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' })   (只安装了 3.4.0)
# 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.

如何解读:#1 的第一条消息点出了错误的值,却归咎于“不允许的元素”—— 有误导性;Import-Module 的消息更清楚。#3 把错误报告在缺失引号的下一行(第 18 行,字符串在那里才结束)—— 往上看一行。#4 和 #5 都通过了 Test-ModuleManifest:它检查的是文件本身,而不是你的意图或其他模块的版本。#5 说“not loaded”,而真正的问题是“找不到 ≥ 5.0.0 的版本”。

# 用 Windows PowerShell 5.1 导入要求 7.4+/Core 的清单
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.

去掉 PowerShellVersion 后,5.1 接受了仅限 Core 的清单,并继续加载 OpsKit.psm1(随后只是因为那台机器上 5.1 自己的执行策略阻止了脚本才停下)。所以 PowerShellVersion 才是真正的关卡;CompatiblePSEditions 是一个标签,供仓库以及 pwsh 对 System32 模块目录中模块的 Windows 兼容性检查使用。

# 不重新生成文件而升级版本
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

目标:给 OpsKit 一个身份:带 0.2.0 版本和显式导出列表的有效清单,然后看看清单能防止什么问题。环境:模块 2 中的 OpsKit。成本:无。

创建清单:使用“命令”分页中的展开传参(保留 GUID,或省略以生成新的 —— 之后就永不更改)。
验证并导入:
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
证明“不要用通配符”:把 OpsKit 复制到 ~/pslab/tmp/exp/wildcard/OpsKit,在那里设置 FunctionsToExport = '*',在新会话中把 ~/pslab/tmp/exp/wildcard 加到 $env:PSModulePath 最前面,然后对比 (Get-Module OpsKit -ListAvailable).ExportedFunctions.Keys 和 Get-Command Get-OpsServer 与显式版本的结果。
故意弄坏它:在 ~/pslab/tmp/bad/OpsKit 下的副本中复现“命令”分页的错误 1、2、4 和 6,并记下 Test-ModuleManifest 能捕获哪些。
清理:Remove-Item ~/pslab/tmp/exp, ~/pslab/tmp/bad -Recurse -Force;Remove-Module OpsKit。

案例 1:“命令存在,但自动加载找不到它”

问题:某团队的模块用 Import-Module 可以正常工作,但其命令从不自动加载,仓库页面上也没有列出任何命令。根本原因:FunctionsToExport = '*' 加上点源加载的 Public 文件。修复:在构建时生成显式列表(模块 8 会检查它与 Public/ 是否一致)。

案例 2:新命令发布了却看不见

问题:发布说明宣布了 Get-OpsHealth;用户却得到“not recognized”。根本原因:文件加进了 Public/,却没加进 FunctionsToExport;Test-ModuleManifest 照样通过。修复:在构建中比较两个列表 —— 模块 8 中复现了这一点。

案例 3:依赖写在代码里,而不是清单里

问题:在新服务器上安装模块后,第一个命令就失败,报“Import-Module: … Az.Accounts not found”。根本原因:.psm1 中调用了 Import-Module Az.Accounts,但清单中没有 RequiredModules,所以安装程序没有把它带上。修复:在 RequiredModules 中带版本范围声明依赖。

常见错误与修复

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

原因:语法错误、数据文件中出现命令或变量,或 RootModule 中的文件名有误。修复:阅读“At line:char”部分(往上看一行),检查名称;Import-PowerShellDataFile 可以对语法给出第二意见。

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

使用 2–4 个数字段。预发布:ModuleVersion = '0.3.0' + PSData 中的 Prerelease = 'beta1'。

The required module 'X' is not loaded

原因:PSModulePath 中没有(所需版本的)X。修复:安装/保存它;检查 RequiredModules 中的版本约束。

requires a minimum PowerShell version of …

在 pwsh 7.x 中运行;只有在真的于更低版本上测试过时,才降低 PowerShellVersion。

导入正常,但缺少某个命令
(Import-PowerShellDataFile ~/pslab/OpsKit/OpsKit.psd1).FunctionsToExport
(Get-ChildItem ~/pslab/OpsKit/Public -Filter *.ps1).BaseName
命令行练习
1. 不导入模块,从清单中打印版本和导出列表。
$d = Import-PowerShellDataFile ~/pslab/OpsKit/OpsKit.psd1
"$($d.ModuleVersion): $($d.FunctionsToExport -join ', ')"
2. 在清单副本中添加对 Pester 5.x(≥ 5.7,< 6)的依赖。
Update-PSModuleManifest -Path ~/pslab/tmp/OpsKit.copy.psd1 -RequiredModules @(@{ ModuleName = 'Pester'; ModuleVersion = '5.7.0'; MaximumVersion = '5.99.99' })

清单用 ModuleVersion(最低)和 MaximumVersion 表达范围;PSResourceGet 的 -Version 使用 NuGet 版本范围(模块 4)。

场景分析
你的模块必须在 Windows PowerShell 5.1 和 pwsh 7 上运行两年。你会设置哪些清单键?如何证明?

PowerShellVersion = '5.1'、CompatiblePSEditions = 'Desktop','Core'、显式导出、不使用仅 7.x 支持的语法(??、三元运算符、-Parallel)—— 再加上一个 CI 矩阵,在 powershell.exe 和 pwsh 中分别导入并测试模块。清单只负责声明,测试才负责证明。

已核实的教学视频

▶
PowerShell Master Class - Advanced Scripting Techniques — John Savill's Technical Training
英文 · 标题和频道已核实;用于了解相关的脚本概念

没有找到专门讲解清单键、导出列表或通配符/自动加载问题的已核实视频;以下文档和本模块的复现结果是参考依据。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:一张写着 OpsKit 0.2.0 的身份证,字段有 RootModule、Exports、Requires。
旁白:清单是模块的身份证,以数据形式读取。
镜头 2 · 20–50 秒
画面:自动加载瞬间读到三个名称;换成 '*' 时它打开盒子,什么也没找到,只好放弃。
旁白:列出你的导出;通配符会把点源加载的函数藏起来。
镜头 3 · 50–75 秒
画面:六张红色错误卡片翻转,其中两张通过了 Test-ModuleManifest。
旁白:验证只抓语法,不抓意图。
镜头 4 · 75–90 秒
画面:版本 0.2.0 → 0.2.1 → 0.3.0 → 1.0.0,分别标注修复 / 功能 / 破坏性变更。
旁白:版本是承诺;绝不重复使用。
或测验得分 ≥ 70%

模块 4 · PSResourceGet:查找、安装、更新与保存;版本范围与信任

21:00 – 28:00 · PowerShell 7.6 自带的 *-PSResource cmdlet 取代了 Install-Module:NuGet 版本范围、明确的安装范围、仓库信任——以及不改动机器任何状态的 Save-PSResource
7 分钟PSResourceGet 1.2.1★★★★☆
学习目标
  • 使用 Find-PSResource、Install-PSResource、Save-PSResource、Update-PSResource、Uninstall-PSResource 和 Get-InstalledPSResource,并了解它们的别名(fdres、isres、svres ……)。
  • 编写 NuGet 版本范围([5.0,6.0)、[5.7.1, ]、精确的 5.9.1)并验证它们解析到哪个版本——包括 1.2.1 中一个范围被解析为最低匹配版本的怪现象。
  • 选择安装范围(CurrentUser / AllUsers),或者根本不用安装范围(Save-PSResource -Path),并在不盲目信任 PowerShell Gallery 的前提下处理仓库信任。
  • 把 PowerShellGet v2 命令对应到 PSResourceGet,并理解为什么 7.6 中两者并存。
前置知识:模块 1–3。重要程度:★★★★☆

是什么:一个模块,三代包管理

PackageManagement(OneGet)+ PowerShellGet v2PSResourceGet(原名“PowerShellGet v3”)
命令Find-Module、Install-Module、Update-Module、Save-Module、Publish-Module、Register-PSRepositoryFind-、Install-、Update-、Save-、Publish-、Compress-PSResource、Register-PSResourceRepository
实现方式构建在 PackageManagement 和 NuGet 提供程序之上的脚本模块单个二进制模块(C#),无需引导提供程序
版本语法-RequiredVersion、-MinimumVersion、-MaximumVersion-Version 加 NuGet 范围
随附于Windows PowerShell 5.1(1.0.0.1)和 pwsh 7.6(2.2.5),为了兼容pwsh 7.4+(7.6:1.2.1);也可安装到 5.1
状态仅维护积极开发中(1.3 预览版)

为什么:版本范围与安装范围

-Version含义2026-11-24 的 Pester
5.9.1恰好此版本5.9.1
5.7恰好 5.7(.0)——不是“5.7 或更高”5.7.0
[5.7.1, ]≥ 5.7.1(包含下限需要用方括号形式)8 个版本,最新 6.2.0
[5.0, 6.0)≥ 5.0 且 < 6.0——“任意 5.x”24 个版本,最新 5.9.1
(, 5.0]≤ 5.055 个版本
*任意(配合 Find:列出全部)82 个稳定版本
安装位置Windows(pwsh 7)Linux/macOS需要管理员
-Scope CurrentUser(默认)$HOME\Documents\PowerShell\Modules~/.local/share/powershell/Modules否
-Scope AllUsers$env:ProgramFiles\PowerShell\Modules/usr/local/share/powershell/Modules是
Save-PSResource -Path X你选择的任意文件夹(构建目录、离线介质、容器层)否;不登记任何东西

怎么做:仓库信任

PSGallery 注册时是不受信任的。从不受信任的仓库安装会弹出提示;在 -NonInteractive(CI、计划任务)下,提示会变成错误。可选做法:回答提示;对单条命令传入 -TrustRepository;或用 Set-PSResourceRepository -Name X -Trusted 把仓库标记为受信任。微软自己的建议是把 Gallery 当作社区来源:默认不受信任,作为引入包的入口,经你审查后再推广到你自己的受信任包源(模块 5)。

何时用:Install 还是 Save

  • Install 适合你的工作站和长期运行的服务器:模块落在 PSModulePath 上,自动加载可用,由 Get-InstalledPSResource/Update-PSResource 管理。
  • Save 适合构建、容器、隔离网络的服务器和实验:把精确版本下载到你掌控的文件夹,只在该进程中把它加到 $env:PSModulePath 最前面。加上 -IncludeXml,Get-InstalledPSResource -Path 才能识别它们(已验证:不加时该 cmdlet 看不到它们)。
  • Update-PSResource 会把新版本并列安装;它不会删除旧版本,也不会重新加载你的会话。
常见误区① “-Version 5.7 表示 5.7 或更新”——它表示恰好 5.7.0;请写 [5.7, ]。② “范围总会拿到最新的匹配版本”——在 1.2.1 上已验证:Save-PSResource PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' 保存的是 1.22.0,也就是最低版本;务必用 -PassThru 检查,并锁定精确版本以保证可复现。③ “-Version '5.*' 表示 5.x”——已验证:它也返回了 6.x 版本。④ “Update-PSResource 会替换旧版本”——它只是新增一个文件夹。⑤ “到处用 -TrustRepository 没问题”——它关闭了唯一一个询问你是否真的要从互联网拉取代码的提示。

流程图:从版本范围到磁盘上的文件夹

Install-PSResource Pester-Version '[5.0, 6.0)' 按 Priority 排序的仓库数字小者优先;先命中者胜 解析范围用 -PassThru / Find 检查 受信任?否 → 提示 / 错误 下载 .nupkg(+ 依赖)可选 -AuthenticodeCheck 解压到 <安装范围或 -Path>\Pester\5.9.1\移除 NuGet 元数据 · PSGetModuleInfo.xml 不会导入到当前会话——由 Import-Module 或新会话加载(模块 1 的规则)Save-PSResource 在你的文件夹中完成解压即止;-AsNupkg 则保留 .nupkg(本地镜像)
图 4-1:安装程序只是把文件放进版本文件夹;加载什么由模块系统(模块 1)决定

从 -Version 到磁盘上的文件夹

就绪。

命令表

PSResourceGetPowerShellGet v2 对应命令说明
Find-PSResource -Name X [-Version r] [-Prerelease]Find-Module另有 -Tag、-Type Module|Script、-IncludeDependencies
Install-PSResource X -Version r -Scope CurrentUserInstall-Module-TrustRepository、-Reinstall、-AcceptLicense、-AuthenticodeCheck、-PassThru
Save-PSResource X -Path dir [-IncludeXml | -AsNupkg]Save-Module无安装范围,不登记任何东西
Update-PSResource XUpdate-Module并列安装
Get-InstalledPSResource [X] [-Path dir]Get-InstalledModule只能看到带 PSGetModuleInfo.xml 的包
Uninstall-PSResource X -Version vUninstall-Module
Get-PSResourceRepository、Set-PSResourceRepositoryGet-PSRepository、Set-PSRepository保存在 PSResourceRepository.xml 中(按用户)
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.

如何验证:5.7 是精确版本;5.* 并不是“5.x”(28 = 24 个 5.x + 4 个 6.x)。最后一条错误说“could not be found”,但 Pester 明明存在——它的意思其实是“没有匹配的版本”。常见错误:不看范围解析结果就直接信任它。

# Save:不安装,不登记。先不信任仓库,以非交互方式运行:
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

在交互式会话中,第一条错误会变成一个“You are installing the modules from an untrusted repository … Are you sure?”提示。Get-InstalledPSResource 只列出 6.2.0,因为只有那次保存使用了 -IncludeXml(它会写入 PSGetModuleInfo.xml);Pester 5.9.1 仍然完全可以导入。

# 范围怪现象:命令形式相同,结果相反
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

如何验证:对 PSScriptAnalyzer,范围结果按从旧到新返回,Save 取了第一个(1.22.0);对 Pester,结果按从新到旧返回,Save 取了 5.9.1。不带范围时保存的是最新版(1.25.0)。生产用法:只解析一次范围(先按 Version 排序,再 Find-PSResource … | Select-Object -First 1),然后安装精确版本并记录下来(模块 5 的依赖清单文件)。

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
# 可选——安装到你自己的 CurrentUser 模块文件夹(未在实验机上运行):
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          # 撤销
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…

目标:获取第 4–8 课需要的工具——Pester 和 PSScriptAnalyzer——而不为你的用户安装任何东西。环境:可访问互联网的 pwsh 7.6。成本:~/pslab/modules 中约 3 MB。

浏览版本:Find-PSResource Pester -Version '[5.0,]' 和 Find-PSResource PSScriptAnalyzer。记下 Pester 最新的 5.x 和 6.x。
连同元数据保存精确版本:
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
只在本会话中使用它们,然后重新运行模块 1 的脚本:
$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 字节)。模块 5 会把这样的文件夹变成一个仓库。
清理:保留 ~/pslab/modules(第 8 课会用到);删除镜像:Remove-Item ~/pslab/tmp/mirror -Recurse。

案例 1:一个悄悄让代码检查工具降级的“版本范围”

问题:构建脚本用 PSScriptAnalyzer -Version '[1.22.0, 2.0.0)' 保存,想“拿到最新的 1.x”;新规则却始终没有出现。根本原因:在 PSResourceGet 1.2.1 上,这个范围解析成了 1.22.0(上文已复现)。修复:在依赖清单文件中锁定精确版本并有计划地更新;在 CI 中记录 -PassThru 的输出。

案例 2:一个从来装不上任何东西的计划任务

问题:一个引导任务在任务计划程序下运行 Install-PSResource Az.Accounts,每晚都失败。根本原因:PSGallery 不受信任 → 弹出提示 → -NonInteractive 报错。修复:从你自己的受信任包源安装(模块 5),或在构建镜像时就保存精确版本;不要在生产主机上对公共 Gallery 使用 -TrustRepository。

案例 3:构建代理上的两个 Pester 版本

问题:本以为 Update-PSResource 能修复旧版本模块中的一个缺陷,但代理仍在使用旧版本。根本原因:更新是并列安装的;某个脚本用 -RequiredVersion 导入了旧版本。修复:更新版本锁定,而不只是更新机器。

常见错误与修复

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

原因:名称错误、范围内没有版本、预发布版本但没加 -Prerelease,或者仓库未注册/不可达。

Find-PSResource X -Version '*' -Prerelease | Select-Object -First 5
Get-PSResourceRepository
PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.(安装/保存时)

原因:在非交互宿主中出现了不受信任仓库的提示(或许可证提示)。修复:使用受信任的内部包源;有意识地使用 -TrustRepository;需要接受许可证时使用 -AcceptLicense。

已经安装,但 Import-Module 仍加载旧版本

PSModulePath 顺序与版本文件夹(模块 1)。Get-Module X -ListAvailable | Format-Table Version, ModuleBase;开一个新会话。

安装到 AllUsers 需要管理员权限……

使用默认的 CurrentUser 安装范围,或在需要全机安装时(镜像、服务器)有意识地以提升权限运行。

命令行练习
1. 找到最新的 Pester 5.x,并把恰好这个版本保存到 ~/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. 显示会被最先搜索的仓库。
Get-PSResourceRepository | Sort-Object Priority, Name | Select-Object -First 1
场景分析
安全团队问:“为什么服务器不能直接从 PowerShell Gallery 运行 Install-PSResource -TrustRepository?”请给出三个理由和一个替代方案。

① 任何人都能向 Gallery 发布;一个仿冒拼写或被入侵的包会以服务器的权限运行。② 对生产工作负载而言,可用性没有保证。③ 不锁定版本时,两台服务器在不同日子可能装到不同版本。替代方案:把审查过的精确版本推广到内部包源(Azure Artifacts、文件共享),在服务器上只把该包源注册为受信任,并通过依赖清单文件安装。

已核实的教学视频

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
英语 · 标题与频道已核实;演示的是较早的 PowerShellGet v2 流程(Install-Module)

没有找到关于 PSResourceGet 1.2 的已核实视频(2026-11-24 的搜索只返回了文章);请参考下方文档。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:Install-Module(旧标志)与 Install-PSResource 并排出现。
讲解:PowerShell 7.6 两者都自带;新工作使用 PSResourceGet。
镜头 2 · 20–50 秒
画面:一条数轴,方括号 [5.0, 6.0) 高亮 5.x;随后“5.7”只高亮一个点。
讲解:括号构成范围;单独一个数字是精确版本。
镜头 3 · 50–70 秒
画面:一道标着“不受信任”的闸门拦住了 CI 机器人。
讲解:不受信任的仓库会弹出提示——而提示在自动化中会失败。
镜头 4 · 70–90 秒
画面:Save-PSResource 把版本文件夹放进 ~/pslab/modules。
讲解:把精确版本保存到你掌控的文件夹中。
或测验得分 ≥ 70%

模块 5 · 仓库与发布:本地与私有源、可复现的安装

28:00 – 35:00 · 仓库就是一个 NuGet 包源——一个存放 .nupkg 文件的文件夹,或者一台服务器。发布会把模块文件夹变成包;固定版本、由文件驱动的安装能让每台机器拿到完全相同的内容
7 分钟~/pslab/repo★★★★☆
学习目标
  • 说明 .nupkg 包含什么(你的文件 + 由模块清单生成的 .nuspec),并用 Compress-PSResource 构建一个。
  • 用 Register-PSResourceRepository -Uri 注册文件夹仓库,用 Publish-PSResource 发布,查找并安装固定版本,再全部撤销。
  • 用 Install-PSResource -RequiredResourceFile(.psd1 或 .json)实现可复现的安装。
  • 了解私有包源的差异:Azure Artifacts 与 GitHub Packages(NuGet v3、凭据、搜索限制)、JFrog、ACR、文件共享。
前置知识:模块 3–4。重要程度:★★★★☆

是什么:包、包源、仓库注册

术语含义OpsKit
包(.nupkg)一个 zip:你的模块文件 + OpsKit.nuspec(id、版本、作者、标签、依赖,均取自模块清单)+ NuGet 簿记文件(_rels/、[Content_Types].xml、package/…psmdcp)OpsKit.0.2.0.nupkg,约 6.3 KB
包源包存放的位置:文件夹 / SMB 共享(支持 PSResourceGet 全部功能)、NuGet v2 服务器或 NuGet v3 服务~/pslab/repo
仓库注册写在你自己的 PSResourceRepository.xml 中的名称 + URI + 信任 + 优先级PSLabLocal(可选步骤)

为什么:在 Gallery 与服务器之间放一个私有包源

微软对 PSResourceGet 的指导非常明确:把 PowerShell Gallery 视为不受信任、由社区维护、不适合作为生产环境的直接依赖;只用它来发现包,把审核过的包提升(promote)到受信任的包源中。你自己的模块本来也需要一个“家”。包源带来:不可变版本、统一的安装来源,以及访问控制。

包源URI 形式安装时的认证说明(PSResourceGet 文档)
文件夹 / 文件共享C:\repo、\\server\psrepo、/mnt/psrepo仅文件系统权限(不支持 -Credential)支持所有搜索场景
Azure Artifactshttps://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed>/nuget/v3/index.json私有包源需要 PAT 或 Azure Artifacts Credential Provider(1.2+)不支持通配符 / 标签 / 命令搜索;发布需要 -ApiKey(任意字符串)+ -Credential(PAT)
GitHub Packageshttps://nuget.pkg.github.com/<owner>/index.json始终需要(PAT)owner 是用户或组织,而不是代码仓库;不支持通配符 / 标签搜索
JFrog Artifactory、MyGet、NuGet.Server、ACRNuGet v3 / …/nuget / https://<registry>.azurecr.io视情况而定自 1.1 起支持 ACR

怎么做:先发布,再安装固定版本

  1. Publish-PSResource -Path ~/pslab/out/OpsKit -Repository PSLabLocal 会验证模块清单、打包文件夹(整个文件夹——先暂存一份干净副本),再把 .nupkg 复制到包源。Compress-PSResource 只做打包,可输出到任意文件夹——在不能或不想注册仓库时很方便。
  2. Install-PSResource OpsKit -Version 0.2.0 -Repository PSLabLocal 精确安装该版本;模块清单中的 RequiredModules 会成为 NuGet 依赖并一并安装(1.2 版对 NuGet v3 包源不会安装依赖——需要自行安装)。
  3. 依赖清单文件(required-resource file)为整个环境列出“名称 → 版本范围 → 仓库”;用 Install-PSResource -RequiredResourceFile 应用它。

何时用:选哪条发布路径

场景做法
笔记本、实验环境、构建产物Compress-PSResource → 文件夹中的 .nupkg
使用共享目录的 Windows 团队SMB 上的文件夹仓库 + Publish-PSResource
有 CI/CD 的组织Azure Artifacts / GitHub Packages;由流水线使用机密发布,绝不从笔记本发布
开源项目使用 API 密钥发布到 PowerShell Gallery(第 8 课)
常见误区①“发布只会打包模块文件”——它打包的是文件夹:笔记、测试、.git 和机密都会进去;请暂存一份干净副本。②“修了 bug 可以重新发布 0.2.0”——包源把版本视为不可变(缓存里也还留着旧内容);请升级到 0.2.1。③“注册仓库是机器级的”——它是用户级的(位于本地应用数据下的 PSResourceRepository.xml);服务账户有自己的列表。④“-Credential 对文件共享有效”——文件共享包源只使用调用者自己的文件系统访问权限。⑤“写了版本范围的依赖清单文件就是可复现的”——只有精确版本才可复现。

架构图:从模块文件夹到另一台机器

~/pslab/out/OpsKitpsd1 · psm1Public/ · Private/(暂存副本) 打包 OpsKit.0.2.0.nupkg文件 + OpsKit.nuspecid · version · tags依赖 = RequiredModules 发布 包源~/pslab/repo(文件夹)\\share · Azure ArtifactsGitHub Packages 安装 目标机器Modules\OpsKit\0.2.0\Import-Module OpsKit-RequiredVersion 0.2.0 谁知道什么 你的用户:PSResourceRepository.xml → Name PSLabLocal · Uri file:///…/pslab/repo · Trusted · Priority 包源:只有 .nupkg 文件(不可变版本) 目标机器:requirements.psd1 → OpsKit = @{ version = '[0.2.0]'; repository = 'PSLabLocal' } 机密(PAT、API 密钥)保存在 SecretManagement 或 CI 机密存储中——绝不写进这些文件
图 5-1:暂存 → 打包 → 包源 → 固定版本安装。每个箭头都是一条可以单独运行(或验证)的命令

发布 → 包源 → 安装 → 导入

就绪。
动画背后的真实机制 对于本地文件夹包源,PSResourceGet 读取 *.nupkg 的文件名及其中的 .nuspec;既没有服务器也没有索引。发布时会在临时文件夹中根据模块清单生成 nuspec,与你的文件一起压缩,再把结果复制到包源。安装时解压到 <scope>/Name/Version/,删除 NuGet 簿记文件并写入 PSGetModuleInfo.xml。

命令表

命令用途说明
Compress-PSResource -Path dir -DestinationPath feed构建 Name.Version.nupkg无需仓库;-PassThru 返回文件
Register-PSResourceRepository -Name N -Uri path -Trusted把包源加入你的列表会修改用户状态;撤销:Unregister-PSResourceRepository N
Publish-PSResource -Path dir -Repository N打包并推送服务器包源用 -ApiKey/-Credential;-NupkgPath 推送现成的包
Find-PSResource -Repository N在单个包源中搜索文件夹包源支持通配符
Install-PSResource X -Version 0.2.0 -Repository N固定版本安装用范围语法写作 -Version '[0.2.0]',效果相同
Install-PSResource -RequiredResourceFile f.psd1安装一整套.psd1 或 .json;也可用 -RequiredResource @{…}
Save-PSResource X -AsNupkg -Path dir把包镜像到文件夹包源从 Gallery 提升到内部包源
# 把 OpsKit 打包到文件夹包源——不注册,~/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>

如何验证:nuspec 中的每个值都来自 OpsKit.psd1;PSModule 标签是自动添加的(Gallery 用它区分模块和脚本)。源文件夹里的一切都被打包了——如果里面有 notes.txt 或 tests/ 文件夹,它们也会在包里。常见错误:直接打包工作文件夹。生产用法:在 CI 中打包暂存副本(模块 8)。

可选:注册一个文件夹仓库(会修改你的仓库列表)

Register-PSResourceRepository -Name PSLabLocal -Uri (Convert-Path ~/pslab/repo) -Trusted -PassThru
Publish-PSResource -Path ~/pslab/out/OpsKit -Repository PSLabLocal        # 模块 8 会构建 ~/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
# 撤销
Uninstall-PSResource -Name OpsKit -Version 0.2.0
Unregister-PSResourceRepository -Name PSLabLocal

为什么标为“预期”:PSResourceGet 1.2.1 把仓库列表保存在固定的用户级文件中(Windows 上为 %LOCALAPPDATA%\PSResourceGet\PSResourceRepository.xml——验证时它忽略了子进程中重定向的 LOCALAPPDATA),因此这些命令无法隔离到实验文件夹。模块 8 和综合实验会把同一个包解压到安装时的确切位置并按版本导入,以此验证它。

可复现的安装

# ~/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 } }
# 可选(安装到 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

同样内容的 JSON 文件(requirements.json)也可用于同一参数。'[0.2.0]' 在 NuGet 语法中表示“恰好 0.2.0”。把该文件和需要它的代码一起提交。

私有包源(概览)

# Azure Artifacts(NuGet v3)。从私有包源安装需要 PAT 或 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(第 7 课)——绝不写明文令牌
Publish-PSResource -Path ./out/OpsKit -Repository CorpFeed -ApiKey 'AzureDevOps' -Credential $cred

# GitHub Packages(NuGet v3,每个操作都需要凭据;owner = 用户或组织)
Register-PSResourceRepository -Name GitHubFeed -Uri 'https://nuget.pkg.github.com/MyGitHubOrg/index.json'

目标:在你的文件夹包源中生成 OpsKit.0.2.0.nupkg,并准确理解其中的内容。环境:带模块清单的 OpsKit(模块 3)。成本:无。注册和安装是可选的。

打包:Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/repo -PassThru。
检查:用“命令”分页中的 ZipFile 命令查看包内条目和 nuspec。哪些模块清单键出现在 nuspec 中?
看清风险:创建内容为 TODO: password = hunter2 的 ~/pslab/OpsKit/notes.txt,打包到 ~/pslab/tmp,然后列出条目:
Set-Content ~/pslab/OpsKit/notes.txt -Value 'TODO: password = hunter2'
$pkg = Compress-PSResource -Path ~/pslab/OpsKit -DestinationPath ~/pslab/tmp -PassThru
Add-Type -AssemblyName System.IO.Compression.FileSystem
$z = [IO.Compression.ZipFile]::OpenRead($pkg.FullName); $z.Entries.FullName | Where-Object { $_ -notmatch '^(_rels|package)/|Content_Types' }; $z.Dispose()
Remove-Item ~/pslab/OpsKit/notes.txt, $pkg.FullName
OpsKit.nuspec
notes.txt
OpsKit.psd1
OpsKit.psm1
Private/ConvertTo-OpsServer.ps1
Private/Resolve-OpsPath.ps1
Public/Get-OpsConfig.ps1
Public/Get-OpsServer.ps1
Public/Test-OpsEndpoint.ps1
模块 8 会暂存一份干净副本,从而杜绝这种情况。
编写依赖清单文件 ~/pslab/requirements.psd1,并用 Import-PowerShellDataFile 检查。
可选(会修改你的用户状态):注册 PSLabLocal,查找并安装 OpsKit 0.2.0,导入它,然后卸载并取消注册。
清理:暂时保留 ~/pslab/repo——模块 8 会用自己的脚本重新构建包(请先删除 ~/pslab/repo/OpsKit.0.2.0.nupkg,否则脚本会拒绝覆盖已发布的版本)。

案例 1:已发布的包里有机密

问题:内部包源上的一个模块包含 dev.settings.json,里面有服务主体的机密。根因:在代码仓库根目录执行 Publish-PSResource -Path .,把一切都打包了。修复:轮换该机密;只暂存模块清单列出的文件(或把 FileList 作为文档,由构建只复制这些文件);在 CI 中扫描包。包源会保留旧版本——仅删除包是不够的。

案例 2:“同一个版本,不同的代码”

问题:两台服务器相隔一周安装了 OpsKit 1.4.0,行为却不同。根因:有人在文件共享包源上删除并重新发布了 1.4.0。修复:让包源只能追加(通过权限),每次改动都升级版本,并在版本已存在时让构建失败(模块 8 的脚本正是这样做的)。

案例 3:流水线无法从私有包源安装

问题:Install-PSResource 在笔记本上正常,在 CI 中访问 Azure Artifacts 时失败。根因:笔记本上有缓存的凭据,代理机上没有。修复:通过 -Credential 传入来自流水线机密存储的 PAT,或配置 Azure Artifacts Credential Provider(PSResourceGet 1.2 起支持),并在作业中注册仓库,而不是写进镜像。

常见错误与修复

Publish/Install 提示仓库不存在
Get-PSResourceRepository

注册是用户级的:服务账户、容器或 CI 作业必须自己注册包源。

发布时提示包已存在 / 版本冲突

升级 ModuleVersion。不要删除后重新发布已发布的版本。

Azure Artifacts 或 GitHub Packages 返回 Unauthorized(401/403)

PAT 缺失或过期、权限范围错误(Azure Artifacts 需要 Packaging 读/写),或 GitHub 包源 URL 中用了代码仓库名而不是 owner。

从 NuGet v3 包源安装时没有安装依赖

PSResourceGet 1.2 不会从 v3 包源安装依赖;请在依赖清单文件中显式列出它们。

命令行练习
1. 不解压,列出任意 .nupkg 中的文件。
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. 把 Gallery 上恰好 6.2.0 版的 Pester 镜像到你的文件夹包源,供离线服务器使用。
Save-PSResource -Name Pester -Version 6.2.0 -AsNupkg -Path ~/pslab/repo -TrustRepository
场景分析
为 300 台可能无法访问互联网的 Windows 服务器设计模块供应链。

内部的 Azure Artifacts(或 SMB)包源是服务器上唯一注册且受信任的仓库。一条提升流水线用 Save-PSResource -AsNupkg 保存审核过的 Gallery 包,扫描后推送进去。你自己的模块由 CI 从暂存的构建发布,版本不可变。服务器应用写有精确版本的依赖清单文件;用 Get-InstalledPSResource 检测漂移。凭据来自机密存储,绝不写在脚本里。

已核实的教学视频

▶
PowerShell Master Class - Automation — John Savill's Technical Training
英语 · 交付模块的自动化背景(标题与频道已核实)
▶
New PowerShell Secrets Management Module - Easily use any secret provider — John Savill's Technical Training
英语 · 包源凭据应当存放在哪里(标题与频道已核实)

没有找到讲解 PSResourceGet 文件夹仓库或 Compress-PSResource 的已核实视频。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:一个模块文件夹被压缩进盖着“OpsKit 0.2.0”印章的箱子,一张由 psd1 打印出的 nuspec 标签贴在上面。
旁白:包就是你的文件夹,加上一张由模块清单生成的标签。
镜头 2 · 25–50 秒
画面:货架(包源)上摆着箱子;一个箱子想用相同的印章替换另一个,被拒绝。
旁白:包源是存放不可变版本的货架。
镜头 3 · 50–75 秒
画面:一张 requirements.psd1 清单让三台服务器装上相同的版本。
旁白:固定版本的文件让安装可复现。
镜头 4 · 75–90 秒
画面:Gallery → 审核关口 → 内部包源 → 服务器。
旁白:先提升,再使用;不要直接从互联网拉取。
或测验得分 ≥ 70%

模块 6 · 提供程序与驱动器:FileSystem、Env、Registry、Cert、Variable、Function

35:00 – 42:00 · 提供程序(provider)让数据存储看起来像文件系统。同样的 Get-ChildItem、Get-Item、New-Item 和 Get-ItemProperty 可用于文件、环境变量、函数、证书和注册表——但各提供程序有自己的规则
7 分钟Get-PSProvider · New-PSDrive★★★☆☆
学习目标
  • 用 Get-PSProvider / Get-PSDrive 列出提供程序和驱动器,并读懂能力(capabilities):它解释了为什么 -Filter 对文件有效、对 Env: 却无效。
  • 用 item 类 cmdlet 操作 Env:、Variable:、Function: 和 Alias:;以只读方式读取 Cert: 和 HKLM:/HKCU:(Windows);区分项(注册表键)与项属性(注册表值)。
  • 用 New-PSDrive 创建指向 ~/pslab/data 的会话驱动器,并理解为什么 .NET 方法看不到 PowerShell 驱动器(Convert-Path)。
前置知识:第 1 课模块 5(PSPath)。重要程度:★★★☆☆

是什么:提供程序与驱动器

提供程序驱动器项是项属性平台
FileSystemC:、/、Temp:文件、文件夹属性、时间(很少用)全部
EnvironmentEnv:当前进程的环境变量—全部
VariableVariable:PowerShell 变量—全部
FunctionFunction:函数和筛选器(包括模块导出的函数)—全部
AliasAlias:别名—全部
CertificateCert:证书存储和 X.509 证书—Windows
RegistryHKLM:、HKCU:键值(名称/数据对)Windows

驱动器是某个提供程序内部的一个具名根。New-PSDrive 可以添加你自己的驱动器:为很深的文件夹、注册表分支或网络共享起一个短名字。驱动器只存在于当前会话中(除非用 -Persist 创建真正的 Windows 映射驱动器)。

为什么:一套动词操作所有存储

Cmdlet文件Env:注册表
Get-ChildItem列出文件夹列出变量列出子键
Get-Item / Test-Path单个文件单个变量单个键
New-Item、Remove-Item、Rename-Item、Copy-Item✓✓(仅限当前进程)✓(键)
Get-Content / Set-Content文件文本值—
Get-ItemProperty、Get-ItemPropertyValue、Set-ItemProperty、New-ItemProperty很少用—值

怎么做:提供程序路径与能力

  • 每个项都带有 PSPath:Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv。这种提供程序限定形式在任何地方都有效,即使路径没有驱动器。
  • 能力说明提供程序支持什么:FileSystem 具有 Filter(高效的原生筛选)和 Credentials;其他提供程序只有 ShouldProcess。在 Env: 上使用 -Filter 会失败;改用 Where-Object 或通配符路径(Env:\PS*)。
  • .NET 方法([IO.File]::ReadAllText)完全不认识 PowerShell 驱动器:请传入 (Convert-Path Lab:\servers.csv)——模块 7 会展示 ~ 的同类问题。

何时用:本课程用到的地方

OpsKit 读取文件(FileSystem)和配置(数据文件);第 7 课读取机密和环境变量(Env:);第 8 课检查代码签名证书(Cert:\CurrentUser\My -CodeSigningCert)。注册表出现在 Windows 资产清点脚本中——可以随意读取,写入则只能通过变更管理流程。

常见误区① “注册表值是项”——值是键的项属性;Get-ChildItem 列出的是子键,而不是值。② “$env:X = 1 是永久设置”——只对当前进程及其子进程有效;持久变量在 Windows 上需要 [Environment]::SetEnvironmentVariable(…, 'User'),在 Linux 上需要写入 shell 配置文件。③ “New-PSDrive 创建的驱动器在资源管理器里可见”——没有 -Persist 就不可见,而且其他进程永远看不到。④ “Get-ChildItem Env: -Filter PS* 可以用”——已验证会报错:该提供程序不支持筛选器。⑤ “Cert: 和 HKLM: 到处都有”——仅限 Windows。

架构图:一个 cmdlet,多个提供程序

Get-ChildItem / Get-Item / New-Item路径 → 驱动器 → 提供程序 FileSystemC: · Lab:Filter ✓ EnvironmentEnv:仅限当前进程 VariableVariable:$x ⇔ Variable:\x FunctionFunction:OpsKit 导出的函数 AliasAlias:gci → Get-ChildItem CertificateCert:Windows RegistryHKLM: · HKCU:键 + 值 PSPath = 提供程序::提供程序路径,例如 Microsoft.PowerShell.Core\FileSystem::C:\Users\labadmin\pslab\data\servers.csv .NET API 只认提供程序路径 → 调用 [IO.File]::… 之前先 Convert-Path Lab:\servers.csv 注册表:键 = 项(Get-ChildItem)· 值 = 项属性(Get-ItemProperty / Get-ItemPropertyValue)
图 6-1:动词是共享的;能力和项的形态因提供程序而异

路径 → 提供程序 → 项

就绪。

命令表

命令用途说明
Get-PSProvider提供程序、能力、驱动器Certificate 在其模块加载后才出现
Get-PSDrive [-PSProvider X]驱动器FileSystem 驱动器会显示可用空间
New-PSDrive -Name Lab -PSProvider FileSystem -Root ~/pslab/data会话驱动器Remove-PSDrive Lab
Get-ItemProperty Key -Name V / Get-ItemPropertyValue Key -Name V注册表值后者直接返回值本身
Convert-Path X、Resolve-Path XPowerShell 路径 → 提供程序路径供 .NET 和原生工具使用
Test-Path Env:\X、Test-Path Function:\Get-OpsServer在任意提供程序中检查是否存在
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.

如何验证:模块导出的函数确实是 Function: 中的项;用 New-Item 创建的别名与 Set-Alias 效果相同。常见错误:在文件系统之外使用 -Filter——请改用 Get-ChildItem Env:\PS* 或 Where-Object Name -like 'PS*'。

# 只读:证书和注册表(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

没错,在 Windows 11 上 ProductName 显示的是“Windows 10 Pro”——这是注册表的老问题;请使用 CurrentBuild(≥ 22000 即 Windows 11)或 Get-CimInstance Win32_OperatingSystem。注册表键是一个 Microsoft.Win32.RegistryKey 对象,它的值是属性。

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
# 不同提供程序使用同样的 item 动词
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

目标:用同一套动词浏览五个提供程序,并为 OpsKit 的数据文件夹创建一个驱动器。环境:pwsh 7.6(Cert/注册表步骤仅限 Windows)。安全:注册表和证书步骤均为只读;环境变量的修改只影响当前进程。成本:无。

概览:Get-PSProvider;Get-PSDrive -PSProvider Environment, Variable, Function, Alias。
仅对一个进程生效的环境变量:设置 $env:OPSKIT_ENV = 'prod',然后证明子进程能看到它、而启动你这个 shell 的父进程看不到:pwsh -NoProfile -Command '$env:OPSKIT_ENV'。用 Remove-Item Env:\OPSKIT_ENV 删除它。
一个 Lab: 驱动器:创建它、列出内容、通过它读取 servers.csv,然后尝试 [IO.File]::ReadAllLines('Lab:\servers.csv'),再用 Convert-Path 修复。
仅限 Windows,只读:列出 Cert:\CurrentUser\My(只看数量),用 Get-ItemPropertyValue 读取 HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion 中的 CurrentBuild,并列出 HKCU:\Software\Microsoft 的子键(只要名称,-Name)。
清理:Remove-PSDrive Lab -ErrorAction Ignore;没有写入其他任何内容。

案例 1:什么也没读到的“注册表读取”

问题:一个资产清点脚本用 Get-ChildItem HKLM:\…\Uninstall\App 读取 DisplayVersion,结果为空。根因:值是项属性;Get-ChildItem 返回的是子键。修复:使用 Get-ItemPropertyValue -Path … -Name DisplayVersion;在 64 位 Windows 上,还要检查 HKLM:\SOFTWARE\WOW6432Node\… 中的 32 位应用。

案例 2:消失的环境变量

问题:一个安装脚本设置了 $env:OPSKIT_CONFIG,之后运行的计划任务却看不到它。根因:Env: 的修改只在当前进程内有效。修复:通过参数传递配置(第 1 课模块 1 的原则),或通过配置管理有意识地设置机器级/用户级变量。

案例 3:只在交互式会话中可用的驱动器

问题:脚本使用了在配置文件(profile)中创建的 Lab:\…;在任务计划程序下运行时报错“Cannot find drive”。根因:驱动器属于会话状态;使用 -NoProfile 时配置文件不会加载。修复:用参数和 Join-Path 构造路径;如果需要驱动器,就在脚本内部创建。

常见错误与修复

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

-Filter 是 FileSystem 的能力。请在路径中使用通配符或改用 Where-Object。

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

新会话、作业或另一个运行空间。在那里创建驱动器,或使用真实路径。

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

写入 HKLM 需要提升权限;读取某些键也需要。本课只做读取。

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

.NET 不理解 PowerShell 驱动器或 ~:先 Convert-Path。

命令行练习
1. 显示所有名称以 PS 开头的环境变量,并排序。
Get-ChildItem Env:\PS* | Sort-Object Name | Format-Table Name, Value
2. 以整数形式读取 Windows 内部版本号(仅限 Windows)。
[int](Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name CurrentBuild)
场景分析
一位同事希望 OpsKit 把默认环境保存在注册表里,“因为 Windows 就是把设置存在那里的”。请回应。

这会让 OpsKit 只能在 Windows 上运行(Linux/macOS 没有 HKCU:),配置不进入源代码管理,也难以测试。应把配置保留在 opskit.config.psd1 中(可移植、可评审、作为数据安全读取),并允许参数覆盖它。注册表只用于读取 Windows 的系统信息。

已核实的教学视频

▶
PowerShell Master Class - Data and Objects — John Savill's Technical Training
英文 · 对象以及注册表等数据源(标题和频道已核实)
▶
PowerShell For Beginners Full Course | PowerShell Beginner tutorial Full Course — Nerd's lesson
英文 · 入门课程(标题和频道已核实)

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:七个抽屉,分别标着 C:、Env:、Variable:、Function:、Alias:、Cert:、HKLM:,同一个 cmdlet 依次打开它们。
旁白:提供程序让每种存储都像一个驱动器。
镜头 2 · 25–55 秒
画面:一个注册表键打开,露出挂在它上面的一张张“值”卡片。
旁白:键是项,值是项属性。
镜头 3 · 55–75 秒
画面:Lab: 快捷方式指向 ~/pslab/data;一个 .NET 机器人看不懂路牌,直到 Convert-Path 把它翻译出来。
旁白:驱动器只属于 PowerShell;交给 .NET 前先转换路径。
镜头 4 · 75–90 秒
画面:-Filter 撞上 Env: 被弹回。
旁白:能力各不相同——Filter 只用于文件。
或测验得分 ≥ 70%

模块 7 · 跨平台:路径、大小写、编码、换行符与环境变量

42:00 – 50:00 · 同一个 .ps1 要想在 Windows、Linux 和 macOS 上都能运行,就不能硬编码分隔符、不能假设文件名不区分大小写,必须有意识地选择编码,并以可移植的方式拆分文本和路径
8 分钟Join-Path · Format-Hex★★★★☆
学习目标
  • 用 Join-Path、Split-Path(-Leaf、-LeafBase、-Extension)和 [IO.Path] 构造路径,并知道 ~ 和相对路径会在哪里让 .NET 调用出错。
  • 依据 $IsWindows/$IsLinux/$IsMacOS 分支,避免使用仅限 Windows 的 cmdlet,或为其加上保护。
  • 用 Format-Hex 证明编码:pwsh 7 写入无 BOM 的 UTF-8;Windows PowerShell 5.1 的 > 写入 UTF-16 LE,Set-Content 写入 ANSI 代码页。
  • 拆分文本时处理 CRLF 与 LF 的差异,并用 [IO.Path]::PathSeparator 拆分 $env:PATH。
前置知识:模块 1 和模块 6。重要程度:★★★★☆

是什么:真正重要的差异

主题WindowsLinux / macOS可移植写法
目录分隔符\(也接受 /)只有 /Join-Path;字面量中的 / 两边都能用
路径列表分隔符(PATH、PSModulePath);:[IO.Path]::PathSeparator
文件名大小写不敏感(NTFS 默认)敏感(Linux),默认不敏感(macOS APFS)处处使用准确的大小写
环境变量名不敏感($env:path = $env:PATH)敏感准确的大小写
Set-Content 写入的换行符CRLFLF按 '\r?\n' 拆分;在意时显式使用 "`n" 写入
默认编码(pwsh 7)所有 cmdlet 和 > 均为无 BOM 的 UTF-8使用方需要其他编码时加 -Encoding
隐藏文件文件属性以点开头-Force
ls、cat、sort 等别名PowerShell 别名原生工具使用完整的 cmdlet 名称(第 1 课)

为什么:编码——Windows PowerShell 5.1 是怎么做的

写入方式pwsh 7.6Windows PowerShell 5.1
Set-Content、Add-ContentUTF-8,无 BOM“Default” = 系统 ANSI 代码页(多数西文系统为 1252;实验机上是 UTF-8,因为它开启了“使用 Unicode UTF-8 提供全球语言支持”选项,ACP 为 65001)
>、Out-FileUTF-8,无 BOM带 BOM 的 UTF-16 LE(FF FE)
-Encoding UTF8无 BOM 的 UTF-8(要 BOM 用 utf8BOM)带 BOM 的 UTF-8
读取无 BOM 的文件按 UTF-8按 ANSI → 在 1252 系统上 café 变成 café

大多数问题出现在文件跨越边界时:保存为无 BOM UTF-8 的脚本由 5.1 运行(非 ASCII 字符串字面量会乱码);5.1 用 > 写出的 CSV 被 Linux 工具当作二进制文件;或者 BOM 破坏了 shebang 行或 JSON 解析器。

怎么做:OpsKit 的规则

  • 路径:Join-Path $HOME 'pslab' 'data'、$PSScriptRoot,绝不写 "$HOME\pslab"。
  • 调用 .NET 之前:先 Convert-Path(它基于 PowerShell 当前位置解析 ~、驱动器和相对路径;而 .NET 用的是进程目录——见下文验证)。
  • 供其他工具读取的文本输出:-Encoding utf8NoBOM(7.x 的默认值,显式写出是为了方便读者以及做 5.1 兼容性检查);只有 Windows 使用方要求时才加 BOM。
  • 源文件:UTF-8;如果脚本必须在 5.1 中运行并且包含非 ASCII 文本,就带 BOM 保存。
  • 仓库:一个 .gitattributes,例如 * text=auto eol=lf,仅当只能在 Windows 上运行的工具需要 CRLF 时再加 *.ps1 text eol=crlf——一次决定,统一执行。

何时用:平台判断

if ($IsWindows) { Get-Service -Name W32Time } else { systemctl is-active chronyd }   # 5.1 中 $IsWindows 未定义 → $null → 走 else 分支!

在同样需要支持 5.1 的代码中,请写 if ($PSVersionTable.PSEdition -eq 'Desktop' -or $IsWindows)。7.6 中仅限 Windows 的命令包括 Registry/Certificate 提供程序、Get-Service、Get-CimInstance、Get-WinEvent、Get-Counter 以及 Import-Module -UseWindowsPowerShell(为仅支持 5.1 的模块提供的 Windows 兼容功能)。

常见误区① “Join-Path 会解析 ~”——已验证:它返回字面量 ~\pslab\data\servers.csv,.NET 随后会去找一个名为 ~ 的文件夹。② “UTF-8 就是 UTF-8”——有没有 BOM 对解析器很重要,而且 5.1 的 -Encoding UTF8 是带 BOM 的。③ “Get-Content -Raw + -split "`n" 得到干净的行”——对 CRLF 文件,每一行末尾都会残留 `r(已验证:web-01 的长度为 7)。④ “在 Windows 上能用,大小写就没问题”——Linux 不会同意。⑤ “$IsWindows 到处都有”——5.1 中没有。

字节级视图:同一个词,五种编码

在 Windows 上写入 'café' + 换行(字节来自 Format-Hex,已验证) pwsh 7 Set-Content / > 63 61 66 C3 A9 0D 0A UTF-8,无 BOM(é = C3 A9) -Encoding utf8BOM EF BB BF 63 61 66 C3 A9 0D 0A 开头是 BOM EF BB BF 5.1 > / Out-File FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00 UTF-16 LE,BOM FF FE Windows-1252 (ANSI) 63 61 66 E9 0D 0A 每个字符一个字节 LF only ("`n" join) 63 61 66 C3 A9 0A Linux 工具期望的格式
图 7-1:文本相同,字节不同。把 UTF-8 字节按 1252 读取,C3 A9 就变成了“é”

流程图:让路径可移植

"$HOME\pslab\data"在 Linux 上出错 Join-Path $HOME pslab data正确的分隔符 Convert-Path绝对路径,~ 已解析 .NET / 原生工具各平台指向同一文件 还要保持大小写准确:在 Linux 上 ~/pslab/data/servers.csv ≠ ~/pslab/DATA/Servers.csv
图 7-2:分隔符、解析、大小写——路径不可移植的三种相互独立的原因

同一个脚本,Windows 与 Linux 对比

就绪。
关于 Linux 一侧 Windows 结果均在 7.6.10 上实际运行。Linux 行为(文件名大小写敏感、: 分隔符、缺少 Windows cmdlet)依据官方文档,标注为预期结果;你可以在 mcr.microsoft.com/powershell 容器或 Linux 虚拟机中运行实验亲自验证。

命令表

命令用途说明
Join-Path $a b c用正确的分隔符拼接可接多个子路径(7.x);不解析 ~
Split-Path $p -Parent | -Leaf | -LeafBase | -Extension拆解路径-LeafBase/-Extension 为 7.x 新增
[IO.Path]::Combine()、::Join().NET 拼接Combine 遇到带根的片段会从头开始
[IO.Path]::DirectorySeparatorChar、::PathSeparator\//、;/:
Convert-Path绝对的提供程序路径在调用 .NET 之前使用
Format-Hex -Path f显示字节编码的真相
-Encoding utf8NoBOM | utf8BOM | unicode | ascii | 1252选择编码7.x 接受代码页编号
$IsWindows、$IsLinux、$IsMacOS、$PSVersionTable.Platform平台判断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

如何验证:Windows 找到了 SERVERS.CSV——甚至按你输入的大小写报告名称,而不是真实的 servers.csv,所以大小写错误在 Windows 上完全不可见。在 Linux 上 Test-Path 返回 False。Combine 丢掉了 pslab,因为 C:\data 是带根的路径。

~/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
# .NET 调用中的 ~ 和相对路径
[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 把相对路径 ~\… 相对于进程目录(pwsh 启动时所在的目录)解析,而不是你的 PowerShell 当前位置——一行代码里藏着两个错误。Convert-Path 一并修复。

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 字节按 ANSI 解码
Get-Content enc-1252.txt                         # 把 ANSI 字节按 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�
# 在 Windows PowerShell 5.1 中做同样的写入,再从 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

如何验证:5.1 的 > 和 Out-File 写出了 UTF-16 LE;-Encoding UTF8 加上了 BOM。Set-Content 写入的是系统 ANSI 代码页——这里之所以是 UTF-8,只是因为这台机器的 ACP 为 65001((Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Nls\CodePage).ACP);在典型的 1252 系统上,它会像 enc-1252.txt 一样写出 63 61 66 E9 0D 0A。生产实践:只要文件会被其他程序读取,就显式写明 -Encoding。

# 拆分时的 CRLF 与 LF
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

目标:让 OpsKit 风格的代码可移植,并在字节层面证明编码。环境:pwsh 7.6;第 3 步需要 Windows PowerShell 5.1(Windows);第 5 步可选使用 Linux 容器。成本:无。

审查 OpsKit:Get-ChildItem ~/pslab/OpsKit -Recurse -Include *.ps1, *.psm1 | Select-String -Pattern '\\', ';' -SimpleMatch。在实验机上它找到了四行,没有一行是路径:Resolve-OpsPath 中的 [\\/] 正则表达式、两行帮助注释和一个哈希表——OpsKit 的所有路径都用 Join-Path 构造,并在 Resolve-OpsPath 中解析 ~。
pwsh 7 中的编码:在 ~/pslab/tmp 中运行“命令”分页里的 Show-Bytes 代码块。
5.1 中的编码(Windows):运行那行 powershell.exe 命令并比较结果。用原理部分的注册表命令查看你机器的 ANSI 代码页——你的 ps51-setcontent.txt 是 UTF-8 还是 1252?
换行符:用 -split "`n" 重现 `r 问题,再用 '\r?\n' 修复。
可选,Linux:docker run --rm -it -v "$HOME/pslab:/root/pslab" mcr.microsoft.com/powershell:lts pwsh,然后运行 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。

案例 1:被 Linux 当成二进制文件的 CSV

问题:一个每晚运行的 5.1 作业用 > 导出 servers.csv;Linux 上的 ETL 看到 NUL 字节后失败。根因:5.1 重定向产生的 UTF-16 LE。修复:在 5.1 中使用 Export-Csv -Encoding UTF8(带 BOM),或把作业迁移到 pwsh 7(无 BOM 的 UTF-8);用 Format-Hex 验证。

案例 2:在 Windows 上能导入、在 Linux 容器中却不能的模块

问题:Import-Module opskit 在笔记本上可以运行,在 Linux CI 容器中却失败。根因:文件夹名是 OpsKit;Linux 文件名大小写敏感,而且模块内部的 . $PSScriptRoot/public/x.ps1 大小写也写错了。修复:处处使用准确的大小写;在 CI 中用 Linux 容器运行测试(第 8 课)。

案例 3:多出来的回车符

问题:从在 Windows 上编辑过的文件中读取名称后,比较 $name -eq 'web-01' 永远不成立。根因:-split "`n" 在每行末尾留下了 `r。修复:使用不带 -Raw 的 Get-Content(它会去掉换行符),或按 '\r?\n' 拆分;为仓库设置 .gitattributes。

常见错误与修复

带重音的字符显示为 é 或 �

写入方与读取方的编码不一致。用 Format-Hex 检查字节;用正确的 -Encoding 读取;有意识地写入 UTF-8。

Cannot find path '/home/…/SERVERS.CSV'(Linux),但在 Windows 上正常

大小写敏感。使用准确的文件名;Get-ChildItem -Name 可以显示它。

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

某个 .NET API 收到了 ~ 或相对路径。先 Convert-Path。

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

仅限 Windows 的 cmdlet。用 if ($IsWindows) 保护,或使用原生工具(systemctl)。

含非 ASCII 字符串的脚本在 pwsh 中正常,在 5.1 中乱码

5.1 把没有 BOM 的脚本按 ANSI 读取。如果脚本必须由 5.1 运行,请保存为带 BOM 的 UTF-8。

命令行练习
1. 在任意操作系统上逐行输出 PATH 中的每一项。
$env:PATH -split [IO.Path]::PathSeparator
2. 为一个挑剔的使用方,把 report.csv 写成带 BOM、LF 换行的 UTF-8。
$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 必须既能在 Windows 笔记本上运行,又能在 CI 的 Linux 容器中运行。列出你会加入代码评审的检查项。

不硬编码 \ 或 ;;调用 .NET 前使用 Join-Path/Convert-Path;文件名大小写准确;不使用别名;用 $IsWindows 保护仅限 Windows 的 cmdlet;对其他工具会读取的文件显式指定 -Encoding;按 '\r?\n' 拆分文本;再加一个在 Linux 上导入并测试模块的 CI 作业。

已核实的教学视频

▶
PowerShell 7 Overview — John Savill's Technical Training
英文 · 跨平台的 PowerShell 7(标题和频道已核实)
▶
Getting Ready for DevOps with PowerShell and VS Code — John Savill's Technical Training
英文 · 编辑器与工作流,包括 VS Code 中的文件编码(标题和频道已核实)

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:一条反斜杠路径在企鹅的桌子上碎成几段;Join-Path 把它重新拼好。
旁白:让 Join-Path 来选择分隔符。
镜头 2 · 20–50 秒
画面:'café' 的字节排成五行,每种编码高亮一行。
旁白:文本相同,字节不同——Format-Hex 告诉你真相。
镜头 3 · 50–70 秒
画面:末尾藏着一个 ␍ 的 'web-01' 在相等比较中失败。
旁白:CRLF 会留下一个回车符。
镜头 4 · 70–90 秒
画面:SERVERS.CSV 在 Windows 上找到了,在 Linux 上找不到。
旁白:Windows 原谅大小写,Linux 不会。
或测验得分 ≥ 70%

模块 8 · OpsKit v0.2:打包为模块并发布到本地仓库

50:00 – 60:00 · 把前面的内容串起来:对照 Public/ 验证模块清单,暂存一份干净副本,打包或发布 0.2.0 版本,然后在干净的会话中安装并按版本导入
10 分钟Publish-OpsKit.ps1★★★★★
学习目标
  • 描述 OpsKit v0.2 的最终目录结构以及每个文件的用途。
  • 编写 Publish-OpsKit.ps1:Test-ModuleManifest、导出列表 = Public/ 文件名、干净的暂存、拒绝覆盖已发布版本、Compress-PSResource 或 Publish-PSResource。
  • 把包安装到模块文件夹(与 Install-PSResource 的做法相同),并用 -RequiredVersion / -MinimumVersion 导入;看懂版本不存在时的错误。
  • 使用排错树处理“模块加载不了 / 命令找不到”。
前置知识:模块 1–5。重要程度:★★★★★(这是第 5–8 课的基础里程碑)

是什么:OpsKit v0.2

路径作用是否进入包?
~/pslab/OpsKit/OpsKit.psd1身份:0.2.0、RootModule、三个导出、PowerShell 7.4+、Core是
~/pslab/OpsKit/OpsKit.psm1加载器:模块状态、点源 Private + Public、导出是
Public/Get-OpsConfig.ps1、Get-OpsServer.ps1、Test-OpsEndpoint.ps1对外 API是
Private/Resolve-OpsPath.ps1、ConvertTo-OpsServer.ps1辅助函数是(不导出)
~/pslab/scripts/Publish-OpsKit.ps1发布脚本否
~/pslab/out/OpsKit/被打包的暂存副本就是包的内容
~/pslab/repo/OpsKit.0.2.0.nupkg发布版本—

为什么:用发布脚本代替手敲四条命令

模块 3 和模块 5 中的每个生产案例都是手工失误:漏掉的导出、通配符、被打包的机密、被覆盖的版本。脚本把每条教训都变成每次都会运行的检查——第 8 课中,同一个脚本会在 CI 中运行。

怎么做:发布脚本

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

何时用:安装并按版本导入

  • 有已注册仓库时:Install-PSResource OpsKit -Version 0.2.0 -Repository PSLabLocal(模块 5,可选)。
  • 没有注册仓库时(本实验):把 .nupkg 解压到 ~/pslab/modules/OpsKit/0.2.0/ 并删除 NuGet 簿记文件——与安装产生的目录结构相同——然后在当前会话中把 ~/pslab/modules 加入 PSModulePath。
  • 使用方固定版本:脚本中用 Import-Module OpsKit -RequiredVersion 0.2.0、#Requires -Modules @{ ModuleName = 'OpsKit'; RequiredVersion = '0.2.0' },或在自己的模块清单中写 RequiredModules。
常见误区①“实验时直接打包源文件夹没关系”——这个习惯迟早会把机密发出去;请先暂存。②“版本已存在就覆盖它”——发布版本是不可变的;脚本会拒绝。③“在我的会话里测过 = 测过”——你的会话里有点源残留和旧版本模块;请在 pwsh -NoProfile 中测试。④“-MinimumVersion 0.3.0 会退回到 0.2.0”——它会失败,而这正是你想要的。

流程图:v0.2 发布流水线

Test-ModuleManifest语法 · 版本 导出 = Public/Compare-Object 暂存~/pslab/out/OpsKit 版本已存在?是 → 停止 打包 / 发布OpsKit.0.2.0.nupkg 安装目录结构Modules/OpsKit/0.2.0/(7 个文件) 干净的 pwsh -NoProfileImport-Module OpsKit -RequiredVersion 0.2.0 验收:版本 0.2.0 · 恰好 3 个导出 · 辅助函数隐藏 · 从包中加载 · prod = 6 台服务器综合实验在 Test-OpsKitPackage.ps1 中自动执行这些检查
图 8-1:每个方框都是模块 1–5 学到的一条教训,变成了自动检查

发布流水线:哪次运行能通过?

动画下方是针对模块加载问题的交互式排错树。

就绪。

交互式排错树:我的模块或命令加载不了

命令表

命令用途说明
./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose验证、暂存、打包到 ~/pslab/repo无需注册仓库
./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal同上,但发布到已注册的包源可选
Expand-Archive pkg.nupkg -DestinationPath Modules/OpsKit/0.2.0手工生成安装目录结构然后删除 _rels、package、[Content_Types].xml、*.nuspec
Import-Module OpsKit -RequiredVersion 0.2.0精确版本不存在则失败
Get-Module OpsKit -ListAvailable装了什么、装在哪里
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

在控制台中,throw 会显示为 Exception: …\Publish-OpsKit.ps1:44,后面跟着消息框;这里做了简化。来自 Compress-PSResource 的 VERBOSE 行显示了生成 nuspec 的临时文件夹。

# 导出检查能发现忘记更新的模块清单
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-PSResource 生成的目录结构,然后按版本导入
$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          # 自动加载 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

如何验证:命令是从已安装的副本自动加载的(ModuleBase 位于 modules\OpsKit\0.2.0 下),而不是从源文件夹。常见错误:针对 ~/pslab/OpsKit 测试,却交付了别的东西。生产用法:CI 中对构建出的包执行同样的步骤(第 8 课)。

目标:把 OpsKit 0.2.0 发布到 ~/pslab/repo,并按版本使用它。环境:模块 2–3 中的 OpsKit。成本:无;~/pslab 之外不会有任何改动。

保存发布脚本为 ~/pslab/scripts/Publish-OpsKit.ps1(见“原理”分页)。如果模块 5 留下了 ~/pslab/repo/OpsKit.0.2.0.nupkg,先删除它。
发布:./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose;再运行一次,读一读拒绝信息。
破坏导出约定:新建 Public/Get-OpsHealth.ps1,观察脚本停止,然后删除该文件。
安装并按版本导入:使用“命令”分页中的命令;然后在一个全新的进程中:
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,用 Update-PSModuleManifest 升级到 0.2.1 后运行 ./scripts/Publish-OpsKit.ps1 -Repository PSLabLocal;用 Unregister-PSResourceRepository PSLabLocal 撤销。
清理:保留 ~/pslab/repo 和 ~/pslab/modules/OpsKit——第 5 课从 0.2.0 开始。~/pslab/out 随时可以删除。

案例 1:测试本身的 bug,被测试发现了

问题:编写本课的验收脚本时,“包内文件数”检查报告的是 8 而不是 7。根因:Remove-Item -Path …\[Content_Types].xml 把 [Content_Types] 当作通配符字符类(第 1 课模块 7),于是该文件被悄悄地漏删了。修复:使用 -LiteralPath。测试之所以能发现它,是因为它精确地数了文件个数——验收检查要做得精确。

案例 2:“从源码运行是好的”

问题:一个发布版本通过了所有本地运行,但用户那里失败了:包里缺少一个 Private 文件。根因:测试导入的是 ~/src/Module,而不是构建出的包;构建的复制步骤有拼写错误。修复:测试你实际交付的产物(综合实验正是这样做的)。

案例 3:脚本之间的版本漂移

问题:OpsKit 0.3.0 上架包源后,一个旧的计划任务脚本因为某个默认值变了而出错。根因:它导入 OpsKit 时没有指定版本。修复:在自动化中固定版本(#Requires … RequiredVersion),并根据变更日志有计划地升级。

常见错误与修复

Version 0.2.0 is already in … Bump ModuleVersion

这是预期行为。执行 Update-PSModuleManifest -Path ~/pslab/OpsKit/OpsKit.psd1 -ModuleVersion 0.2.1;如果只是练习,也可以删除实验用的包。

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

<=:文件存在但未导出 → 把它加入模块清单。=>:导出了名称但没有对应文件 → 删除该名称或创建文件。

The specified module 'OpsKit' with version 'x' was not loaded …
Get-Module OpsKit -ListAvailable | Format-Table Version, ModuleBase
$env:PSModulePath -split [IO.Path]::PathSeparator
命令来自源文件夹而不是已安装的副本

查看 (Get-Command Get-OpsServer).Module.ModuleBase。移除模块,开启新会话,按名称 / 版本导入。

命令行练习
1. 把 OpsKit 升级到 0.2.1 并发布,不动 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. 让脚本在没有恰好 0.2.0 版 OpsKit 时拒绝运行。
#Requires -Modules @{ ModuleName = 'OpsKit'; RequiredVersion = '0.2.0' }
场景分析
你的发布脚本通过了,但同事安装后说“Get-OpsServer is not recognized”。请逐步诊断。

① 哪个 PowerShell?($PSVersionTable;模块清单要求 7.4。)② 是否安装在 PSModulePath 搜索的位置?(Get-Module OpsKit -ListAvailable。)③ 已安装的模块清单是否导出了它?((Get-Module OpsKit -ListAvailable).ExportedFunctions。)④ 自动加载是否被关闭,或会话已过时?(在新会话中执行 Import-Module OpsKit -RequiredVersion …。)⑤ 是 Linux 吗?文件夹大小写必须是 OpsKit。可以使用“动画”分页中的排错树。

已核实的教学视频

▶
Getting Ready for DevOps with PowerShell and VS Code — John Savill's Technical Training
英语 · 围绕模块的源代码管理和工具(标题与频道已核实)
▶
PowerShell Master Class - Automation — John Savill's Technical Training
英语 · 标题与频道已核实

没有找到演示用 PSResourceGet 把模块打包到文件夹包源的已核实视频;以本模块的脚本和输出为准。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:一排五道关卡(模块清单、导出、暂存、版本、打包),一个包依次通过。
旁白:发布就是一连串的检查。
镜头 2 · 20–45 秒
画面:第二个 0.2.0 包被货架弹了回来。
旁白:永远不要覆盖一个版本。
镜头 3 · 45–70 秒
画面:包展开成 Modules/OpsKit/0.2.0,一个全新的终端导入了它。
旁白:在干净的会话中,按版本测试交付的产物。
镜头 4 · 70–90 秒
画面:路线图 0.2 → 0.3(错误处理)→ 0.4(并行)→ 0.5(云)→ 1.0(测试)。
旁白:OpsKit 现在是一个真正的模块了;下一课让它更健壮。
或测验得分 ≥ 70%

命令速查表

第 4 课全部要点:模块发现、脚本模块、模块清单、PSResourceGet、仓库、提供程序、跨平台规则与发布流程
PowerShell 7.6可复制

1. 查找与加载模块

$env:PSModulePath -split [IO.Path]::PathSeparator
Get-Module                          # 已加载
Get-Module X -ListAvailable         # 已安装(所有版本)
Import-Module X -RequiredVersion 1.2.3 -PassThru
Import-Module ./X -Force            # 修改后重新加载
#Requires -Modules @{ ModuleName='X'; ModuleVersion='5.0.0' }
Module\Command                      # 限定名调用

2. 脚本模块

# X.psm1
$script:State = $null               # 模块作用域
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 } # 查看内部(调试)

3. 模块清单

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
# 绝不要: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' = 恰好 5.7.0 · '[5.7,]' = 5.7 或更高

5. 仓库与发布

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   # 镜像
Unregister-PSResourceRepository Local

6. 提供程序与驱动器

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. 跨平台

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                                   # 字节不会说谎
$text -split '\r?\n'; $env:PATH -split [IO.Path]::PathSeparator

8. 发布流程(OpsKit v0.2)

./scripts/Publish-OpsKit.ps1 -PackageOnly -Verbose
#  模块清单有效 → 导出 = Public/ → 暂存 → 拒绝已存在的版本 → 打包
Expand-Archive repo/OpsKit.0.2.0.nupkg modules/OpsKit/0.2.0   # 安装目录结构
pwsh -NoProfile -Command 'Import-Module OpsKit -RequiredVersion 0.2.0'
./Test-OpsKitPackage.ps1; $LASTEXITCODE        # 0 = 可以交付

综合实验 + 结业测验

编写 ~/pslab/Test-OpsKitPackage.ps1:像安装那样解压已发布的包,在干净的子 pwsh 中按版本导入,并用有意义的退出码验证版本、导出、私有性和行为
约 25 分钟仅本地综合 M1–M8

场景

在任何人安装 OpsKit 0.2.0 之前,团队希望有一道关卡测试包本身,而不是源文件夹。脚本必须:找到 ~/pslab/repo/OpsKit.<version>.nupkg(缺失时退出码 2);把它解压到一个采用安装目录结构的临时模块根目录;启动一个干净的 pwsh -NoProfile -NonInteractive,其 PSModulePath 能看到该根目录;用 -RequiredVersion 导入 OpsKit;以对象形式报告检查结果;全部通过时退出码 0,否则 1;并在结束后自行清理。

脚本(M1、M2、M3、M5、M6、M7、M8)——保存为 ~/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

值得注意的细节:探测代码是一个格式字符串,所以字面量花括号要写两次(@{{);$env:PSModulePath 只在调用子进程前后修改,并在 finally 中恢复;NuGet 簿记文件用 -LiteralPath 删除,因为对 -Path 而言 [Content_Types] 是通配符模式(模块 8 案例 1——这个 bug 正是在编写本实验时出现的)。

运行(在模块 8 构建出 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

当脚本中还留着 -Path 的 bug 时,同样的运行输出了 files in package 7 8 False、警告 1 check(s) failed: files in package 以及 exit=1——失败路径同样可用。

验收标准

开放式自检

1. 逐步解释:当 PSModulePath 中包含 ~/pslab/modules 时,一个全新会话运行 Get-OpsServer 会发生什么。

没有已加载的命令匹配;自动加载按顺序扫描 PSModulePath,找到 ~/pslab/modules/OpsKit/0.2.0/OpsKit.psd1,读取 FunctionsToExport(仅作为数据)并看到该名称;检查 PowerShellVersion,然后在新的模块作用域中运行 OpsKit.psm1(设置 $script: 状态、点源 Private 和 Public、Export-ModuleMember);导出过滤(psm1 ∩ 模块清单)导入三个函数;命令运行,并在模块作用域内调用私有辅助函数。

2. 为什么模块清单的导出列表和 psm1 的 Export-ModuleMember 同时存在?以谁为准?

模块清单中的列表是供发现、安装器和 Gallery 使用的静态元数据;Export-ModuleMember 控制代码在运行时导出什么。只有两者都允许的函数才会被导出。

3. 举出三种模块“在我机器上能跑”、到了服务器上却不行的情况。

PSModulePath 中更靠前的位置有另一个版本(或 Windows 自带的 Pester 3.4);依赖配置文件的状态或驱动器;Linux 上路径区分大小写;仓库没有为服务账户注册或不受信任;数据文件的编码 / 换行符不同。

4. 要在 Linux 上的 CI 中运行 Test-OpsKitPackage.ps1,需要改什么?

路径方面什么都不用改——它使用 Join-Path 和 [IO.Path]::PathSeparator;只需确保数据文件夹存在(或让 Get-OpsServer -Path 指向测试用 CSV),并用 pwsh -File 运行,使退出码能传给 CI 系统。

来源与版本说明

版本事实于 2026-11-24 对照 Microsoft Learn、PowerShell Gallery 和 YouTube oEmbed 核实;命令输出来自 PowerShell 7.6.10 和 Windows PowerShell 5.1.26100
核实日期 2026-11-24
主题核实结果来源(访问于 2026-11-24)
自带的包管理工具pwsh 7.6.10 自带 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 在 7.6 中失败本课的实际运行;What's New in PowerShell 7.6
模块发现Windows 上 PSModulePath 的条目与顺序;自动加载;PSModulePath 中第一个包含该模块的条目胜出,即使后面的条目有更新的版本;Windows PowerShell 文件夹中的 Pester 3.4.0;从 Pester 6.2.0 切换到 5.9.1 时的程序集重新加载失败about_Modules;about_PSModulePath;about_Requires;实际运行
脚本模块没有 Export-ModuleMember 时:函数被导出,变量和别名不导出;模块作用域状态;-Force 重新加载Export-ModuleMember;PowerShell 101: Script modules;实际运行
模块清单New-ModuleManifest 的输出;通配符 FunctionsToExport 会让发现机制看不到点源的函数;六条错误消息;阻止 5.1 的是 PowerShellVersion,而不是 CompatiblePSEditionsabout_Module_Manifests;New-ModuleManifest;Test-ModuleManifest;实际运行
PSResourceGetNuGet 版本范围的行为(5.7 为精确版本、[x, ]、5.* 也包含 6.x);PSScriptAnalyzer 的版本范围解析为最低匹配版本;不受信任的仓库 + -NonInteractive 报错;Get-InstalledPSResource -Path 需要 -IncludeXml。2026-11-24 的 Gallery:Pester 6.2.0 / 5.9.1、PSScriptAnalyzer 1.25.0、SecretManagement 1.1.2Install-PSResource(版本语法、依赖清单格式、安装范围);Save-PSResource;about_PSResourceGet;实际运行
仓库文件夹、Azure Artifacts、GitHub Packages、JFrog、MyGet、NuGet.Server、ACR 的配置与限制;Gallery 应视为不受信任;1.3 预览版把 Microsoft Artifact Registry 加为默认仓库Supported repository configurations;Working with local PSRepositories;Publish-PSResource;Compress-PSResource
提供程序提供程序能力、Env/Variable/Function/Alias 的项操作、只读的 Cert: 与注册表查询、Env: 上的 -Filter 错误about_Providers 及各提供程序的 about 主题;实际运行
跨平台7.6 与 5.1 的字节级编码(实验机 ACP 65001)、CRLF 拆分、.NET 调用中的 ~、Windows 不区分大小写的查找about_Character_Encoding;Writing portable modules;实际运行
OpsKit v0.2Publish-OpsKit.ps1 和 Test-OpsKitPackage.ps1 在 7.6.10 上运行;包 6.3 KB,7 个模块文件;全部 8 项验收检查通过本课的实际运行

视频核实说明

只列出 2026-11-24 通过 YouTube oEmbed(https://www.youtube.com/oembed?url=…&format=json)核实过标题和频道的视频。John Savill 的视频来自他的“PowerShell Master Class”播放列表(PLlVtbbG169nFq_hR7FcMYg32xsSAObuq8,同样经 oEmbed 核实):

oEmbed 只核实标题和频道;视频并未逐段观看,“meta”行描述的是标题所暗示的主题。这些视频大多早于 PowerShell 7.6 和 PSResourceGet;凡是演示 Install-Module 或 Windows PowerShell 5.1 行为的地方,以本课为准。2026-11-24 的网络搜索没有找到关于 PSResourceGet 1.2、模块清单导出列表或 Compress-PSResource 的可核实视频。

语音讲解说明

“语音”分页使用浏览器内置的 Web Speech API 朗读讲解稿(zh-CN);不需要网络访问或外部脚本。本课件无法嵌入 MP3 文件或生成视频;讲解稿和分镜可交给 TTS 或视频工具使用。

已知局限

  • 运行环境:“实际输出(7.6.10)”产生于 Windows 11(build 26300)上的 pwsh 7.6.10,运行在一个子进程中,其 HOME/USERPROFILE 指向临时文件夹(因此 ~/pslab 是隔离的),PSModulePath 以 Windows 默认的机器级值为起点;路径已替换为 C:\Users\labadmin\…,并在较长的临时路径导致列换行的地方调整了表格宽度。错误记录以交互式控制台打印的单行形式展示。
  • 未运行(会修改状态):Register-PSResourceRepository、发布到已注册仓库的 Publish-PSResource、Install-PSResource、Update-PSResource、Uninstall-PSResource、Install-PSResource -RequiredResourceFile、Set-PSResourceRepository。PSResourceGet 1.2.1 把仓库列表保存在固定的用户级文件中(它忽略了重定向的 LOCALAPPDATA),因此无法隔离;这些输出标为“预期”。包本身通过 Compress-PSResource 以及解压到安装目录结构进行了验证。
  • 未在 Linux/macOS 上运行:大小写敏感、: 分隔符、Linux 模块路径以及缺失的 Windows cmdlet 均取自文档,并标为“预期”。
  • 5.1 中 Set-Content 的编码结果取决于系统 ANSI 代码页;实验机使用 65001(UTF-8),因此 1252 的行为改用 pwsh 中的 -Encoding 1252 展示。
  • 版本范围解析的怪异行为(PSScriptAnalyzer 取最低匹配,Pester 取最新)是 2026-11-24 在 PSResourceGet 1.2.1 上针对 PowerShell Gallery 观察到的;未调查原因,后续版本可能变化。
  • 动画做了简化:省略了模块分析缓存细节、嵌套模块、ScriptsToProcess 以及 NuGet 依赖解析。