Writing a VB script to monitor battery percentage. If it is > 95, then unplug. If < 20, plug in charger or else hibernate and so on. When battery goes below 20%, there is a popup Plug-in charger… and though within 10 sec system is plugged, it goes to else
part and hibernates. It does not enter "System won't hibernate" part.
hibernate.bat
is a simple batch script to hibernate Windows7.
The code is a never ending for
loop, in which do while loop is used to replicate 'continue' in shell scripting. When battery reaches 20%, there is 10 sec time given to plugin charger. If charged, then it has to go to next for loop iteration. "If charged" loop is not being entered. Why?
Set oLocator = CreateObject("WbemScripting.SWbemLocator")
Set oServices = oLocator.ConnectServer(".","root\wmi")
Set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity")
For Each oResult In oResults
iFull = oResult.FullChargedCapacity
Next
For i=1 To 10
Do
i=+2
Set oResults = oServices.ExecQuery("select * from batterystatus")
For Each oResult In oResults
iRemaining = oResult.RemainingCapacity
Charging = oResult.Charging
Discharging = oResult.Discharging
Next
iPercent = ((iRemaining / iFull) * 100) Mod 100
If Charging And (iPercent > 95) Then
MsgBox "Unplug Charger. Battery is at " & iPercent & "%", vbInformation, "Battery monitor"
ElseIf Discharging And (iPercent < 20) Then
MsgBox "Plug-in Charger. Battery is at " & iPercent & "%", vbInformation, "Battery monitor"
WScript.Sleep 10000 ' 10 sec
If Charging Then
CreateObject("WScript.Shell").Popup "System won't hibernate", 5, "Good News!!!"
Exit Do
Else
Set shell = CreateObject("WScript.Shell")
shell.CurrentDirectory = "C:\Users\abcd\Desktop"
CreateObject("WScript.Shell").Popup "System will hibernate", 5, "Hmm..."
shell.Run "hibernate.bat"
Exit For
End If
End If
Loop While False
Next