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

如何在PowerShell脚本中检测任务计划程序因电池切换停止选项终止脚本?

解决方案

要应对任务计划程序因「切换至电池电源时停止任务」选项终止脚本的问题,有两种实用思路:

1. 捕获终止信号,被动触发提示

当任务计划执行停止操作时,会向进程发送终止信号(带UI的托盘脚本通常先收到WM_CLOSE消息,超时后会被强制终止)。你可以通过.NET API监听窗口关闭事件,在脚本被终止前弹出提示:

Add-Type @"
using System;
using System.Windows.Forms;

public class TrayGuard : Form
{
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        // 识别外部触发的关闭操作(含任务计划的终止指令)
        if (e.CloseReason == CloseReason.TaskManagerClosing || e.CloseReason == CloseReason.UserClosing)
        {
            MessageBox.Show("检测到任务计划因电源切换终止脚本,请打开任务计划程序,关闭「切换至电池电源时停止任务」选项!");
        }
        base.OnFormClosing(e);
    }
}
"@

$trayForm = New-Object TrayGuard
$trayForm.Visible = $false
# 此处添加你的托盘图标初始化逻辑
[System.Windows.Forms.Application]::Run($trayForm)

⚠️ 注意:如果任务计划强制终止进程(比如脚本未及时响应关闭信号),该提示可能无法触发。

2. 主动监控电源状态,提前预警

相比被动等待终止,更稳妥的方式是实时监控电源模式切换,一旦检测到从交流转电池,立刻检查任务计划设置并提示用户:

代码示例

# 注册电源状态变更监听事件
Register-WmiEvent -Class Win32_PowerManagementEvent -Action {
    $batteryStatus = Get-WmiObject -Class Win32_BatteryStatus
    # PowerStatus=1表示当前使用电池供电
    if ($batteryStatus.PowerStatus -eq 1) {
        $targetTaskName = "你的任务计划名称"
        $task = Get-ScheduledTask -TaskName $targetTaskName -ErrorAction SilentlyContinue
        
        if ($task -and $task.Settings.StopIfGoingOnBatteries) {
            Add-Type -AssemblyName System.Windows.Forms
            [System.Windows.Forms.MessageBox]::Show("当前任务计划开启了「切换至电池电源时停止任务」选项,脚本即将被终止,请前往任务计划程序修改设置!", "电源切换警告", 0, 48)
        }
    }
}

# 脚本启动时先检查一次任务设置
$targetTaskName = "你的任务计划名称"
$task = Get-ScheduledTask -TaskName $targetTaskName -ErrorAction SilentlyContinue
if ($task -and $task.Settings.StopIfGoingOnBatteries) {
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show("注意:当前任务计划开启了「切换至电池电源时停止任务」选项,拔电源后脚本会被终止,请前往任务计划程序修改设置!", "初始化警告", 0, 48)
}

# 此处添加你的托盘常驻逻辑
while($true) { Start-Sleep 1 }

💡 提示:Get-ScheduledTask需要管理员权限,若脚本以普通用户运行,可让用户手动输入任务名称,或调整任务计划的权限配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:45:32