基于Chocolatey的PowerShell软件安装脚本问题修复与优化请求
Chocolatey自动化安装脚本优化实现
优化点说明
- 新增管理员权限校验:避免非管理员权限安装导致软件仅对当前用户生效、不显示在控制面板全局程序列表的问题
- 替换
choco install为choco upgrade:天然满足「未安装则自动安装、已安装有新版本则升级、已为最新版本则跳过」的需求,无需额外编写校验逻辑 - 新增通用安装参数:强制全局安装、开启桌面快捷方式生成,解决无应用入口问题
- 新增环境变量刷新逻辑,避免刚安装完Chocolatey后无法识别命令的问题
- 优化输入交互提示,使用更符合中文用户的操作指引
优化后完整代码
# 校验管理员权限 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host "请使用管理员权限运行此脚本" -ForegroundColor Red Read-Host "按回车键退出" exit 1 } # Step 1) 必要时安装Chocolatey if (-not (Test-Path -Path "$env:ProgramData\Chocolatey\choco.exe" -PathType Leaf)) { Set-ExecutionPolicy Bypass -Scope Process -Force [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) # 刷新环境变量确保choco命令可直接调用 $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") } # Step 2) 定义可安装的软件包列表 $Packages = 'googlechrome','firefox','codeblocks','windbg','nasm', 'explorersuite','pestudio','vscode','sysinternals','python' # Step 3) 定义菜单展示函数 function Show-Menu { Clear-Host Write-Host "**********************************************" Write-Host "可用软件列表" for ($i = 0; $i -lt $Packages.Count; $i++) { Write-Host ('{0,2}. {1}' -f ($i + 1), $Packages[$i]) } Write-Host " q. 退出脚本" Write-Host "*************************************************" Write-Host } # Step 4) 主循环逻辑 while ($true) { Show-Menu $UserInput = Read-Host "输入要安装的软件对应序号" if ($UserInput -eq 'q') { break } if ([int]::TryParse($UserInput,[ref]$null) -and 1..$Packages.Count -contains [int]$UserInput) { $packageIndex = [int]$UserInput - 1 $selectedPkg = $Packages[$packageIndex] Write-Host "正在处理 $selectedPkg..." -ForegroundColor Green # 使用upgrade命令自动处理安装/升级/跳过逻辑,增加安装参数确保生成快捷方式、全局安装 choco upgrade $selectedPkg -y --install-arguments="ALLUSERS=1 DESKTOPSHORTCUT=1 QUICKLAUNCHSHORTCUT=0" --accept-license Write-Host "$selectedPkg 处理完成" -ForegroundColor Green } else { $availableOptions = 1..$Packages.Count -join ',' Write-Host "输入无效,请选择 $availableOptions 或 q" -ForegroundColor Red } $null = Read-Host "按回车键继续" }
效果说明
- 所有软件默认全局安装,会正常显示在控制面板的程序列表中
- 桌面快捷方式默认生成,若部分特殊包未生成可手动调整对应包的专属安装参数
- 重复选择已安装的软件会自动跳过安装流程,有新版本时自动升级
内容的提问来源于stack exchange,提问作者Shravan Meghavath
相关产品推荐
相关产品推荐

