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

如何通过PowerShell检测Windows即将到来的重启?

检测Windows即将重启(5分钟内)并触发脚本有序关闭

核心实现思路

Windows在自动更新触发重启时,会生成带精确倒计时的系统信号,我们可以通过两种可靠方式捕获这类信号,避免脚本被突然终止:

1. 解析shutdown.exe查询结果

shutdown /query会返回当前挂起的重启/关机任务详情,包含明确的倒计时时长,适合脚本定期轮询检测:

function Test-ImminentReboot {
    $shutdownOutput = shutdown /query 2>&1
    # 适配中文系统输出
    if ($shutdownOutput -match "将在 (\d+) 分钟内关闭") {
        $remainingMinutes = [int]$matches[1]
        return $remainingMinutes -le 5
    }
    # 适配英文系统输出
    if ($shutdownOutput -match "will shutdown in (\d+) minutes") {
        $remainingMinutes = [int]$matches[1]
        return $remainingMinutes -le 5
    }
    return $false
}

2. 实时监控系统事件日志

系统触发重启计划时,会在System日志中写入Event ID 1074(来源User32),事件描述包含重启倒计时,适合实时监听:

function Register-RebootMonitor {
    $eventFilter = @"
    *[System[Provider[@Name='User32'] and EventID=1074]]
    and *[EventData[Data[@Name='Message'] contains 'restart' and Data[@Name='Message'] contains 'minutes']]
"@
    $eventWatcher = New-Object System.Management.EventWatcher($eventFilter)
    while ($true) {
        $event = $eventWatcher.WaitForNextEvent()
        $message = $event.Properties['Message'].Value
        if ($message -match "(\d+) minutes") {
            $remainingMinutes = [int]$matches[1]
            if ($remainingMinutes -le 5) {
                Invoke-ScriptCleanup
                exit
            }
        }
        Start-Sleep -Seconds 10
    }
}

function Invoke-ScriptCleanup {
    # 替换为你的实际清理逻辑
    Write-Host "开始有序关闭:关闭数据库连接..."
    # 示例:$dbConnection.Close()
    Write-Host "完成基础清理,脚本即将退出。"
}

脚本集成方案

在你的7×24运行脚本中,启动后台任务持续监控重启信号:

# 启动重启监控后台任务
Start-Job -ScriptBlock {
    function Test-ImminentReboot {
        $shutdownOutput = shutdown /query 2>&1
        if ($shutdownOutput -match "将在 (\d+) 分钟内关闭") {
            $remainingMinutes = [int]$matches[1]
            return $remainingMinutes -le 5
        }
        if ($shutdownOutput -match "will shutdown in (\d+) minutes") {
            $remainingMinutes = [int]$matches[1]
            return $remainingMinutes -le 5
        }
        return $false
    }

    function Invoke-ScriptCleanup {
        # 自定义清理逻辑:关闭服务、清理临时文件等
        Write-Host "执行脚本有序关闭流程..."
        # 示例:Stop-Service -Name "YourService" -Force
    }

    while ($true) {
        if (Test-ImminentReboot) {
            Invoke-ScriptCleanup
            exit
        }
        Start-Sleep -Seconds 30
    }
}

# 主业务逻辑(你的7×24运行代码)
while ($true) {
    Write-Host "脚本正常运行中..."
    # 替换为你的业务代码
    Start-Sleep -Seconds 60
}

注意事项

  • 脚本需以管理员权限运行,否则shutdown /query可能无法获取完整信息
  • 多语言系统需调整正则表达式匹配对应语言的提示文本
  • 域环境下组策略触发的重启,同样会生成Event ID 1074,该方法依然有效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:05:21