从 services.msc 停止 windows 服务时是否可以触发脚本执行?

Is it possible to trigger a script execution when stopping a windows service from services.msc?

我想知道是否可以将服务配置为在我从 services.msc 停止时调用 batch/powershell 脚本。

虽然在 Linux init.d 中服务是完全可编程的,甚至 systemd 服务也可以有额外的过程,但我还没有找到在 Windows.[=12 上完成此操作的方法=]

提前致谢

您可以将服务配置为 运行 程序失败,但如果您通过 services.msc 停止服务,那么这可能不会算作失败。

我能想到的唯一其他选择是将 PowerShell 脚本 运行ning 设置为定期检查服务 运行ning 状态的计划任务,或者(为了更万无一失的选项)查看事件日志中指示服务已停止的事件(自上次脚本检查以来),然后执行您需要的任何操作。

根据 montonero 的评论,您不需要定期 运行 计划任务,因为它可以配置为 运行 当事件本身发生时。此处对此进行了描述:https://blogs.technet.microsoft.com/wincat/2011/08/25/trigger-a-powershell-script-from-a-windows-event/

Use the Event Viewer “Attach Task to This Event…” feature to create the task.

Launch "Event Viewer" and find the event. Once found, right-click on the event and select "Attach Task to This Event...".