You need to enable JavaScript to run this app. PowerShell如何判断卸载向导中用户是否点击了取消按钮
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell如何判断卸载向导中用户是否点击了取消按钮

解决卸载向导ExitCode无法区分完成/取消的方案

针对当前uninstall.exe返回值异常的场景,可通过以下两种方案实现场景区分,优先推荐第一种可靠性更高的方案:

  • 检测核心资源是否存在(适配所有卸载模式,包括你当前使用的/q静默模式)

卸载流程执行完成后,Erlang的核心运行文件、安装目录内的卸载程序本身、系统注册表中的卸载登记项都会被移除,而用户点击取消时所有资源都会保留,直接检测对应资源即可判断卸载是否实际执行:

$erlInstallPath = "C:\Program Files\erl-23.2"
$uninstallRegPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"

# 启动卸载进程
$proc = Start-Process "$erlInstallPath\Uninstall.exe" -ArgumentList "/q" -PassThru -Wait

# 同时检测核心程序文件和注册表卸载项,不存在则说明卸载完成
$uninstallSuccess = (-not (Test-Path "$erlInstallPath\bin\erl.exe")) `
-and (-not (Get-ItemProperty $uninstallRegPath | Where-Object {$_.DisplayName -match "Erlang.*23\.2"}))

if ($uninstallSuccess) {
    # 此处放你需要执行的后续清理代码
    Write-Host "卸载完成,执行后续清理"
} else {
    Write-Host "用户取消卸载,跳过清理流程"
}
  • UI自动化检测用户操作(仅适配非静默交互模式)

如果你未使用/q参数走交互卸载流程,可以调用Windows UI自动化接口监听用户按钮点击行为,该方案需要提前适配卸载向导的按钮文本、窗口属性,适配性较低,仅作为备选:

# 加载UI自动化依赖
Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes

$proc = Start-Process "C:\Program Files\erl-23.2\Uninstall.exe" -PassThru
$userCanceled = $false

# 监听卸载窗口操作
do {
    Start-Sleep -Milliseconds 300
    if (-not $proc.HasExited -and $proc.MainWindowHandle) {
        $window = [System.Windows.Automation.AutomationElement]::FromHandle($proc.MainWindowHandle)
        $cancelBtn = $window.FindFirst([System.Windows.Automation.TreeScope]::Descendants, 
            [System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::NameProperty, "取消"))
        # 检测取消按钮是否被点击
        if ($cancelBtn -and $cancelBtn.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Cached.IsInvoked) {
            $userCanceled = $true
            break
        }
    }
} while (-not $proc.HasExited)

if (-not $userCanceled) {
    # 执行清理代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 01:06:02