请求修复PowerShell安装Microsoft Visual C++ 2015-2022的检测脚本
修复Visual C++ Redistributable检测与安装脚本
原脚本存在以下问题导致检测失效:
- 使用
Win32_Product查询:该类会触发MSI自动修复操作,查询效率低,且匹配的名称过于宽泛,无法精准识别2015-2022版本的x64/x86组件 - 未区分x64和x86架构:仅做全局存在性检测,无法单独判断两个版本的安装状态
- 条件判断逻辑错误:若查询结果为空,
$MSRedistributable.name会报错,且无法处理部分安装的情况
修复后的脚本
$installerPath = "C:\Software" $vcVersions = @( @{ Name = "Microsoft Visual C++ 2015-2022 Redistributable (x64)" Installer = "$installerPath\VC_redist_2015-2022x64.exe" RegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" Filter = { $_.DisplayName -like "*Microsoft Visual C++ 2015-2022*Redistributable*(x64)*" } }, @{ Name = "Microsoft Visual C++ 2015-2022 Redistributable (x86)" Installer = "$installerPath\VC_redist_2015-2022x86.exe" RegistryPath = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" Filter = { $_.DisplayName -like "*Microsoft Visual C++ 2015-2022*Redistributable*(x86)*" } } ) Write-Host "`n开始检测并安装Microsoft Visual C++ 2015-2022 Redistributable" foreach ($vc in $vcVersions) { $isInstalled = Get-ItemProperty -Path $vc.RegistryPath -ErrorAction SilentlyContinue | Where-Object $vc.Filter if (-not $isInstalled) { Write-Host "正在安装 $($vc.Name)..." Start-Process -FilePath $vc.Installer -ArgumentList "/Q" -Wait -NoNewWindow Write-Host "$($vc.Name) 安装完成" } else { Write-Host "$($vc.Name) 已安装,跳过" } } Write-Host "`n所有Visual C++组件检测与安装操作完成"
修复说明
- 改用注册表查询:通过读取卸载注册表项(x64对应常规路径,x86对应Wow6432Node路径)检测安装状态,避免
Win32_Product的副作用 - 分架构独立检测:分别对x64和x86版本做精准匹配,确保每个版本的状态都能被正确识别
- 循环处理安装:逐个判断每个组件的安装状态,已安装则跳过,未安装则执行静默安装(
/Q参数) - 增强错误处理:添加
-ErrorAction SilentlyContinue避免注册表项不存在时抛出错误
内容的提问来源于stack exchange,提问作者jimmyafflick
相关产品推荐
相关产品推荐

