You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Windows Registry循环无法终止:版本检测逻辑异常求助

修复PowerShell程序安装循环检测的问题

你的代码核心问题是只在循环开始前读取一次注册表中的版本号,之后循环内再也不会更新这个值。如果一开始注册表项不存在、DisplayVersion为空,或者安装过程中版本从旧变新,循环都会因为判断条件一直不满足而无法终止。

修正后的代码:

$targetVersion = [Version]"22.1.30.45"
$uninstallPath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\{AA3C5F33-570B-3989-8542-D5DC0F759221}'

do {
    # 每次循环都重新读取注册表,处理项不存在的情况
    $currentVersion = $null
    if (Test-Path -Path $uninstallPath) {
        $regProps = Get-ItemProperty -Path $uninstallPath -ErrorAction SilentlyContinue
        if ($regProps -and $regProps.DisplayVersion) {
            $currentVersion = [Version]$regProps.DisplayVersion
        }
    }

    # 输出当前状态方便调试(可选)
    Write-Host "当前检测到的版本: $currentVersion"

    Start-Sleep -Seconds 5
} until ($currentVersion -eq $targetVersion)

关键改动说明:

  • 将目标版本和注册表路径抽成变量,方便后续修改
  • 每次循环都重新检查注册表项是否存在,并读取最新的DisplayVersion
  • 增加了错误处理,避免因注册表项不存在或读取失败导致脚本崩溃
  • 可选的Write-Host可以帮助你实时看到检测状态,调试时更直观

内容的提问来源于stack exchange,提问作者brendan smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:06:54