3

I'm trying to run a VBScript checking the time until it reaches 22:00 (10PM), and then runs shutdown.bat. I always get errors such as "'loop' without 'do'". Can anyone look at my code and see if there's a way to fix it?

Do 
    If Hour(Time()) => 22 And Minute(Time()) => 30 And Hour(Time()) < 23 Then
Loop Until True
    Then
        'Dim shell
        Set shell = CreateObject("WScript.Shell")
        shell.Run "shutdown.bat"
        Set shell = Nothing
    End If
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
H3153N
  • 31
  • 2
  • 2
  • 4
    use the [Windows Task Scheduler](https://www.evermap.com/AutoBatchUseTaskScheduler.asp) for that – Slai Jan 29 '17 at 00:29

2 Answers2

4

If you really want to keep a loop running until it reaches a specific hour, here's how it's done:

Do While True ' = Do the following forever (or until something breaks the loop)
    If Hour(Time()) => 22 And Minute(Time()) => 30 And Hour(Time()) < 23 Then
        ' Do whatever you want and then
        ' break the loop:
        Exit Do
    End If
Loop

However, I wouldn't recommend that because it will consume much resources. Instead, you should be using Task Scheduler.

Hope that helps :)

  • Wouldn't you want to use `Do Until True` instead of `Do While True` or are the two interchangeable? – H3153N Jan 29 '17 at 00:56
  • @H3153N, `While True` doesn't mean "while the condition is true". `While True` is always true, so you're basically running the loop infinitely until something breaks it. I added an explanation to my answer above. – 41686d6564 stands w. Palestine Jan 29 '17 at 01:12
2

Loop until the current time is greater than your desired end time:

endtime = CDate("22:30")
Do Until Time > endtime
  WScript.Sleep 100
Loop
CreateObject("WScript.Shell").Run "shutdown.bat"

Using WScript.Sleep inside the loop ensures that the loop doesn't do a burn-in on the CPU.

However, as @AhmedAbdelhameed already mentioned, creating a scheduled task that runs shutdown.bat at the desired time would usually be far more efficient.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328