PLEASE NOTE: This was requested by a user, I was not able to test the script fully as I do not have my laptop set up this way, if my battery < 20% it turned on the plug of my printer.
This is a PowerShell script with a loop that checks the battery at 1 minute intervals and visually show battery percentage and turn Kasa plug on at 20% and off at 80%.
Create a text file called KasaSmartLaptopBatteryMonitor.ps1
and save it (make sure you do not have hidden file extensions otherwise it will be .ps1.txt)
Enable PowerShell Script Execution
Steps to enable PowerShell script execution:
Open PowerShell as Administrator:
- Click Start, type
PowerShell
- Right-click Windows PowerShell and select Run as administrator
Check current execution policy:
Get-ExecutionPolicy
Set the execution policy to allow scripts:
Common choices:
RemoteSigned
— Allows running local scripts and scripts signed by a trusted publisher.Unrestricted
— Allows running all scripts.
Example to set to RemoteSigned (Recommended):
Set-ExecutionPolicy RemoteSigned
run script with
PowerShell KasaSmartLaptopBatteryMonitor.ps1
This script presumes your laptop plug is called “LAPTOP”, if not change $deviceName = "LAPTOP"
to the correct name.
If this works, I would suggest removing the while loop, and sleep delay and running it every minute as a task schedule.
# PowerShell script to control Kasa device based on battery level
# Turns ON at 20% or less
# Turns OFF at 80% or more
# Parse "Relay: 0" or "Relay: 1" from KasaCmd -status output
# Device name set in $deviceName variable
$deviceName = "LAPTOP"
while ($true) {
# Get battery info
$battery = Get-WmiObject -Class Win32_Battery
$charge = $battery.EstimatedChargeRemaining
# Get Kasa device state
$statusOutput = KasaCmd -device "$deviceName" -status
$relayLine = $statusOutput | Where-Object { $_ -match 'Relay:\s*[01]' }
$relayValue = if ($relayLine -match 'Relay:\s*(\d)') { $matches[1] } else { -1 }
$status = if ($relayValue -eq 1) { "on" } elseif ($relayValue -eq 0) { "off" } else { "unknown" }
Write-Host "Battery: $charge% | Device status: $status"
if ($charge -le 20 -and $status -ne "on") {
Write-Host "Battery low - Turning ON '$deviceName'"
KasaCmd -device "$deviceName" -on
}
elseif ($charge -ge 80 -and $status -ne "off") {
Write-Host "Battery high - Turning OFF '$deviceName'"
KasaCmd -device "$deviceName" -off
}
Start-Sleep -Seconds 60
}