PowerShell 模块安装与源配置

一、检查 PowerShell 版本

在开始前,先确认 PowerShell 版本:

1
$PSVersionTable.PSVersion

建议使用 PowerShell 5.1 或以上 版本(Windows 自带)或 PowerShell 7+ (Core)


二、配置 PowerShell 源(在线安装)

PowerShell 模块默认从官方仓库 PowerShell Gallery 获取。
如果系统未配置或访问受限,可以手动注册。

1. 注册 PSGallery 源

1
Register-PSRepository -Default

或者

1
2
3
4
Register-PSRepository -Name "PSGallery" `
-SourceLocation "https://www.powershellgallery.com/api/v2/" `
-ScriptSourceLocation "https://www.powershellgallery.com/api/v2/items/psscript/" `
-InstallationPolicy Trusted

说明:
如果提示 “Use ‘Register-PSRepository -Default’” 或 “The repository already exists”,可先清除后重新注册:

1
2
Unregister-PSRepository -Name "PSGallery" -ErrorAction SilentlyContinue
Register-PSRepository -Default

2. 设置代理(如需)

如果需要通过 HTTP/HTTPS 代理访问:

1
2
[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy('http://proxy_ip:port')
[system.net.webrequest]::defaultwebproxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

或设置全局环境变量:

1
2
setx HTTP_PROXY  "http://proxy_ip:port"
setx HTTPS_PROXY "http://proxy_ip:port"

3. 安装模块

例如安装 PSWindowsUpdate 模块:

1
Install-Module -Name PSWindowsUpdate -Repository PSGallery -Force

可选参数:

  • -Scope CurrentUser :仅安装到当前用户目录(无需管理员权限)
  • -AllowClobber :覆盖同名命令
  • -Force :跳过确认提示

4. 查看与卸载模块

1
2
Get-InstalledModule
Uninstall-Module -Name PSWindowsUpdate

三、离线安装 PowerShell 模块

如果机器无法访问外网,可使用另一台有网机器下载模块包再导入。

1. 在有网络的电脑上下载模块

1
Save-Module -Name PSWindowsUpdate -Path "D:\PSModules"

下载结果示例:

1
2
3
4
5
D:\PSModules\PSWindowsUpdate\
├── 2.2.0.2\
│ ├── PSWindowsUpdate.psd1
│ ├── PSWindowsUpdate.psm1
│ └── ...

2. 将模块目录复制到目标离线机器

复制到以下任意路径:

  • 系统模块目录(管理员权限)

    1
    C:\Program Files\WindowsPowerShell\Modules\
  • 用户模块目录(无需管理员)

    1
    C:\Users\<用户名>\Documents\WindowsPowerShell\Modules\

也可以使用环境变量:

1
$env:PSModulePath

3. 在离线环境导入模块

复制完成后,执行:

1
Import-Module PSWindowsUpdate

验证是否加载成功:

1
Get-Module -ListAvailable PSWindowsUpdate

4. (可选)使用自建本地源

如果希望在局域网内集中管理模块,可建立本地仓库:

1
2
New-Item -Path "D:\LocalPSRepo" -ItemType Directory
Register-PSRepository -Name "LocalRepo" -SourceLocation "D:\LocalPSRepo" -InstallationPolicy Trusted

在联网机器下载模块后复制到该目录,即可在离线机器使用:

1
Install-Module -Name PSWindowsUpdate -Repository LocalRepo

四、常见问题排查

问题 可能原因 解决方法
“Unable to resolve source” 无法访问 PowerShell Gallery 检查网络或代理配置
“未能验证数字签名” PowerShell 执行策略过严 运行 Set-ExecutionPolicy RemoteSigned -Scope Process
“Repository already exists” 已存在同名源 先执行 Unregister-PSRepository -Name PSGallery
“Install-Module 无法连接” TLS 协议过旧 执行 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
模块导入失败 模块路径不正确或缺少依赖 确认模块已复制到正确目录,使用 Get-Module -ListAvailable 检查