/ Powershell

Automatically shutdown your notebook on AC power loss with windows powershell

A short time ago I spend my time searching for a solution to automatically shutdown a notebook when AC power was turned off. After a while I came across the Windows Powershell, which has great features. With a simple script that runs a loop I can fetch the current battery status every 2 seconds. If the script detects, that the system is powered by the battery you can run a custom command. This script only works if the battery is inserted into the notebook. Otherwise Wmi cannot get the battery status.

while(1){


$Bstatus = (Get-WmiObject -Class Win32_Battery -ea 0).BatteryStatus

$Date = Get-Date;

$DateStr = $Date.ToString("HH:mm:ss")

Write-Host $DateStr' Battery status: '$Bstatus

if($Bstatus) {

	switch ($Bstatus){
	
		1 { Write-Host "Battery is discharging" }
		2 { Write-Host "The system has access to AC..." }
		3 { Write-Host "Fully Charged" }
		4 { Write-Host "Low" }
		5 { Write-Host "Critical" }
		6 { Write-Host "Charging" }
		7 { Write-Host "Charging and High" }
		8 { Write-Host "Charging and Low" }
		9 { Write-Host "Charging and Critical " }
		10 { Write-Host "Unknown State" }
		11 { Write-Host "Partially Charged" }            

	}
	
	#Shutdown...
	if($Bstatus -ne 2){
		
		Write-Host "Initializing PC Shutdown in 60 Seconds..."
		
		shutdown -s -t 60 -c "Initializing PC Shutdown in 60 Seconds..."
		
		sleep 30
		
		break
		
	}
	
}else{

	Write-Host "Cannot get battery status :-("
	
}

sleep 2

}