如何编写脚本实现电脑电量低于20%自动休眠并智能循环触发?
Solution: Battery-Triggered Auto-Sleep Service for Windows
I’ve put together a complete solution that meets all your requirements: auto-sleep when battery drops below 20%, prevents immediate re-trigger after reboot until battery rises above 21%, and runs as a persistent Windows service.
Step 1: PowerShell Script (BatteryGuard.ps1)
This script checks battery status, manages trigger state via the Windows Registry, and executes the sleep command when needed. It runs in a loop to monitor battery levels continuously.
# Initialize registry settings if they don't exist $regPath = "HKCU:\Software\BatteryGuardService" if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force | Out-Null New-ItemProperty -Path $regPath -Name "LastTriggered" -Value 0 -PropertyType DWord | Out-Null } # Loop to check battery status every 60 seconds while ($true) { # Get battery information $battery = Get-WmiObject -Class Win32_Battery -ErrorAction SilentlyContinue if (-not $battery) { Write-Host "No battery detected, sleeping for 60 seconds..." Start-Sleep -Seconds 60 continue } $chargeRemaining = $battery.EstimatedChargeRemaining $batteryStatus = $battery.BatteryStatus # 1 = Discharging, 2 = Charging, 3 = Full Write-Host "Current battery level: $chargeRemaining%, Status: $batteryStatus" # Get current trigger state from registry $lastTriggered = (Get-ItemProperty -Path $regPath -Name "LastTriggered").LastTriggered # Reactivate trigger if battery rises above 21% if ($chargeRemaining -gt 21) { if ($lastTriggered -eq 1) { Set-ItemProperty -Path $regPath -Name "LastTriggered" -Value 0 Write-Host "Battery level above 21%, reactivating sleep trigger." } } # Trigger sleep if battery is below 20% (and discharging, not already triggered) elseif ($chargeRemaining -lt 20 -and $batteryStatus -eq 1) { if ($lastTriggered -eq 0) { Write-Host "Battery level below 20%, initiating sleep..." Set-ItemProperty -Path $regPath -Name "LastTriggered" -Value 1 shutdown /h } else { Write-Host "Sleep already triggered, waiting for battery to rise above 21%." } } # Wait 60 seconds before next check Start-Sleep -Seconds 60 }
Key Features:
- Persistent State Tracking: Uses the Windows Registry to remember if sleep was triggered, so the state survives reboots.
- Discharging-Only Check: Only triggers sleep when the battery is actively discharging (avoids unnecessary sleep when plugged in).
- Anti-Flapping Thresholds: Uses 20% (sleep trigger) and 21% (reactivation) to prevent rapid toggling between states.
- Continuous Monitoring: Runs in a loop, checking battery levels every 60 seconds.
Step 2: Set Up as a Windows Service
To run this script as an auto-starting service, we’ll use NSSM (Non-Sucking Service Manager)—a lightweight tool that wraps scripts into proper Windows services.
Install NSSM:
- Download NSSM (match your Windows bitness: 32/64) from its official site.
- Extract the executable to a folder (e.g.,
C:\Tools\NSSM) and add this folder to your system’sPATHfor easy access.
Create the Service:
- Open Command Prompt as Administrator.
- Launch the NSSM installer:
nssm install BatteryGuardService - In the NSSM window:
- Path: Browse to your PowerShell executable (usually
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe). - Arguments: Enter
-ExecutionPolicy Bypass -File "C:\Path\To\Your\BatteryGuard.ps1"(replace with your script’s actual path). - Working Directory: Set to the folder containing your script.
- Path: Browse to your PowerShell executable (usually
- Go to the Log On tab and select "Local System Account" (check "Allow service to interact with desktop" if you want to see script output).
- Go to the Startup Type tab and set it to "Automatic".
- Click Install Service to finish.
Manage the Service:
- Start the service:
net start BatteryGuardService - Stop the service:
net stop BatteryGuardService - Uninstall (if needed):
nssm remove BatteryGuardService confirm
Step 3: Test the Solution
- Unplug your laptop to start discharging the battery.
- Let the battery drop below 20%—your laptop should sleep automatically.
- Wake it up, plug in the charger, and let the battery rise above 21%.
- Unplug again; the script will reactivate and trigger sleep if it drops below 20% again.
- Reboot while the battery is below 20%—it won’t sleep immediately, only after the battery goes above 21% and drops back down.
Notes:
- Execution Policy: The script uses
-ExecutionPolicy Bypassto ensure PowerShell allows it to run. Adjust this if you have strict execution policies. - Battery Detection: If your laptop doesn’t report battery status correctly via WMI, the script will skip checks until a battery is detected.
内容的提问来源于stack exchange,提问作者Sahil Rajput
相关产品推荐
相关产品推荐

