约 2181 字

约 11 分钟

#模块与包管理

#简介

模块是 PowerShell 功能的基本打包单位,通常包含函数、cmdlet、别名和变量。PowerShell Gallery(PSGallery)是公开的模块仓库,PowerShellGet 提供了一组用于查找、安装和更新模块的命令。

PowerShell 7 自带 PowerShellGet。从 PowerShell 7.4 开始,通常还预装了基于 PSResourceGet 的新一代命令(如 Install-PSResource)。

#仓库与查找

使用 Get-PSRepository 查看已注册的仓库。PSGallery 是默认的公共仓库,如果它不存在,可以重新注册:

> Get-PSRepository
> Register-PSRepository -Default
> Find-Module -Name Pester
> Find-Module -Name Pester -AllVersions
> Find-Module -Name Pester -Repository PSGallery

Find-Module 支持按名称查找模块,也可以查看所有版本或指定仓库。

#安装模块

将模块安装到当前用户目录,通常不需要管理员权限:

> Install-Module -Name Pester -Scope CurrentUser
> Install-Module -Name Pester -Scope CurrentUser -Repository PSGallery -Force
  • -Scope CurrentUser 安装到当前用户,AllUsers 通常需要管理员权限。
  • -RequiredVersion 可以安装指定版本。
  • -Force 跳过部分确认提示。
  • -AllowClobber 允许覆盖同名命令。

首次使用 PSGallery 时,PowerShell 可能提示安装 NuGet 提供程序或将仓库标记为受信任。

#更新、卸载与保存

> Get-InstalledModule
> Update-Module -Name Pester
> Uninstall-Module -Name Pester
> Save-Module -Name Pester -Path ./modules

Save-Module 只下载模块,不安装,适合离线分发。目标目录需要事先存在;保存后的模块可以复制到其他计算机,再放入 PSModulePath 包含的目录中使用。

#模块搜索路径

PowerShell 通过 $env:PSModulePath 查找模块。该变量包含多个目录,Windows 上以分号分隔,Linux 和 macOS 上以冒号分隔:

> $env:PSModulePath -split [System.IO.Path]::PathSeparator
> Get-Module -ListAvailable
> Import-Module Pester

如果希望自定义模块被自动发现,应将其放在某个模块路径下,并使用与模块名一致的目录结构。

#Install-PSResource 简介

Install-PSResource 属于 Microsoft.PowerShell.PSResourceGet 模块,是 PowerShellGet 的新一代替代方案。常见命令包括:

> Find-PSResource -Name Pester
> Install-PSResource -Name Pester -Scope CurrentUser
> Update-PSResource -Name Pester
> Uninstall-PSResource -Name Pester
> Save-PSResource -Name Pester -Path ./modules

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2