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

如何阻止运行中的Windows Service在MSI卸载时被自动移除

问题描述

我使用基于WiX的ServiceInstall元素构建MSI安装程序部署Windows服务,服务安装正常,可手动在服务列表中启动它。通过「添加或删除程序」卸载MSI时遇到两种场景:

  • 服务未运行:卸载过程干净(符合预期)
  • 服务运行:MSI仍会自动停止并移除服务

我希望当服务处于运行状态时,卸载能弹出默认Windows提示框(提示用户关闭正在运行的程序)。

当前服务安装代码如下:

new ServiceInstaller
{
    Name = "IP.ServiceInstaller.exe",
    DisplayName = "[IASSERVICENAME]",
    Description = "This is a Service",
    StartOn = null, //set it to null if you don't want service to start as during deployment
    StopOn = SvcEvent.InstallUninstall,
    RemoveOn = SvcEvent.Uninstall_Wait,
    DelayedAutoStart = false,
    ServiceSid = ServiceSid.none,
    FirstFailureActionType = FailureActionType.restart,
    SecondFailureActionType = FailureActionType.restart,
    ThirdFailureActionType = FailureActionType.runCommand,
    RestartServiceDelayInSeconds = 30,
    ResetPeriodInDays = 1,
    PreShutdownDelay = 1000 * 60 * 3,
    Account = "[USERNAME]",
    Password = "[PASSWORD]"
}),
修改方案

核心是调整StopOn和RemoveOn的属性值,让Windows Installer在卸载时不自动停止服务,转而触发系统默认的提示弹窗:

  1. 修改StopOn属性:将SvcEvent.InstallUninstall改为SvcEvent.Install,仅在安装流程中处理服务停止逻辑,卸载阶段不再自动停止服务。
  2. 修改RemoveOn属性:将SvcEvent.Uninstall_Wait改为SvcEvent.Uninstall,移除_Wait后缀后,Windows Installer会在卸载前检查服务状态,若服务运行则弹出默认提示框,等待用户确认后再继续卸载。

修改后的代码片段:

new ServiceInstaller
{
    Name = "IP.ServiceInstaller.exe",
    DisplayName = "[IASSERVICENAME]",
    Description = "This is a Service",
    StartOn = null, //set it to null if you don't want service to start as during deployment
    StopOn = SvcEvent.Install, // 仅安装时处理服务停止
    RemoveOn = SvcEvent.Uninstall, // 卸载时触发系统提示
    DelayedAutoStart = false,
    ServiceSid = ServiceSid.none,
    FirstFailureActionType = FailureActionType.restart,
    SecondFailureActionType = FailureActionType.restart,
    ThirdFailureActionType = FailureActionType.runCommand,
    RestartServiceDelayInSeconds = 30,
    ResetPeriodInDays = 1,
    PreShutdownDelay = 1000 * 60 * 3,
    Account = "[USERNAME]",
    Password = "[PASSWORD]"
}),
原理说明
  • StopOn = SvcEvent.Install:卸载阶段MSI不会主动执行停止服务的操作,保留服务运行状态;
  • RemoveOn = SvcEvent.Uninstall:Windows Installer会自动检测服务运行状态,若服务正在运行则弹出系统默认提示框,告知用户需关闭程序后才能继续卸载,等待用户操作后再完成服务移除流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:57:13