PowerShell检测指定模块是否安装 未安装时友好提示选择安装
PowerShell 自定义模块依赖检测实现
把以下代码放在脚本开头即可替代#requires -Module的默认检测逻辑,实现友好交互:
# 待检测的必需模块列表 $requiredModules = @('AzureAD', 'ExchangeOnlineManagement', 'MSOnline') $missingModules = @() # 遍历检测模块安装状态 foreach ($mod in $requiredModules) { if (-not (Get-Module -Name $mod -ListAvailable)) { $missingModules += $mod } } if ($missingModules.Count -gt 0) { # 自定义友好提示,不触发默认红色报错 Write-Host "`n[提醒] 当前环境缺少以下必需模块:" -ForegroundColor Yellow $missingModules | ForEach-Object { Write-Host " • $_" -ForegroundColor Cyan } # 交互确认 $userChoice = Read-Host "`n是否立即安装缺失模块?输入Y确认,输入其他内容将退出脚本" if ($userChoice.ToLower() -eq 'y') { # 若使用 -Scope AllUsers 全局安装,请保留以下管理员权限校验;当前用户安装可删除这段判断 $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Host "`n[错误] 全局安装模块需要管理员权限,请重启PowerShell以管理员身份运行后重试" -ForegroundColor Red exit 1 } # 配置PSGallery源信任(仅首次运行需要,不会重复修改配置) if ((Get-PSRepository -Name PSGallery).InstallationPolicy -ne 'Trusted') { Set-PSRepository -Name PSGallery -InstallationPolicy Trusted } # 逐个安装缺失模块 foreach ($mod in $missingModules) { Write-Host "`n正在安装模块:$mod" -ForegroundColor Green Install-Module -Name $mod -Scope CurrentUser -Force -AllowClobber -Repository PSGallery } Write-Host "`n所有依赖模块安装完成,继续执行脚本" -ForegroundColor Green } else { Write-Host "`n已取消安装,脚本退出" -ForegroundColor Yellow exit 1 } } else { Write-Host "`n所有依赖模块已就绪,继续执行脚本" -ForegroundColor Green } # 后续自定义脚本逻辑写在此处
关键逻辑说明
- 模块检测用
Get-Module -ListAvailable参数,只会查询本地已安装的模块,不会触发PowerShell默认的强制终止红色报错 - 提示信息用不同前景色区分状态,比原生报错可读性更强:黄色为提醒、青色为列表项、绿色为执行/成功状态、红色为异常
- 安装模块默认用
CurrentUser作用域,给当前登录用户安装,不需要强制提权;如果需要给设备所有用户安装,把-Scope CurrentUser改成-Scope AllUsers即可,配套保留管理员权限校验逻辑 - 自动处理PSGallery源信任问题,避免安装时弹出交互确认打断流程
- 如果需要图形化弹窗而非控制台文本交互,把
Read-Host的交互部分替换为Windows Forms的MessageBox调用即可,控制台场景下Read-Host兼容性最好,适用于所有PowerShell宿主环境。
补充提示
AzureAD、MSOnline属于微软即将停用的旧版Azure AD模块,长期维护的话建议后续迁移到Microsoft Graph SDK模块,当前脚本对你列出的三个模块可以直接正常使用。
内容的提问来源于stack exchange,提问作者LeeGee82
相关产品推荐
相关产品推荐

