编写VB脚本以监控电池百分比。如果是> 95,然后拔下电源插头。如果< 20,插上充电器或者休眠等等。当电池电量低于20%时,会有一个弹出式插入式充电器......虽然在10秒内系统插入,但它会进入else
部分并休眠。它不会进入“系统不会休眠”的部分。
hibernate.bat
是一个简单的批处理脚本来休眠Windows7。
代码是一个永无止境的for
循环,其中while循环用于在shell脚本中复制'continue'。当电池电量达到20%时,插件充电器有10秒的时间。如果收费,则必须转到下一个循环迭代。没有输入“如果收费”循环。为什么呢?
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
答案 0 :(得分:0)
这是你的问题:
ElseIf Discharging And (iPercent < 20) Then
...
If Charging Then
...
Else
...
End If
End If
Charging
和Discharging
状态是彼此相反的。如果Discharging
为真,那么Charging
为假,反之亦然。因此,当您输入Charging
分支时,False
的值始终 ElseIf
。并且由于变量的值反映了分配时的状态,即使在插入电源线后,它仍然 False
。当电池状态改变时,变量不会自动更新。您需要在延迟后重新评估电池状态,以使代码按预期工作。为此,我建议将WMI查找重构为两个函数:
Function IsCharging
For Each oResult In oServices.ExecQuery("SELECT * FROM BatteryStatus")
IsCharging = oResult.Charging
Next
End Function
Function GetRemainingCapacity
For Each oResult In oServices.ExecQuery("SELECT * FROM BatteryStatus")
GetRemainingCapacity = oResult.RemainingCapacity
Next
End Function
并像这样使用它们:
Do
iPercent = ((GetRemainingCapacity / iFull) * 100) Mod 100
If IsCharging And (iPercent > 95) Then
...
ElseIf Not IsCharging And (iPercent < 20) Then
...
If IsCharging Then
...
Else
...
End If
End If
Loop While True