loop until a certain time (in powershell)

Today I needed to write a bit of code that would enable a script to run for 23 hours and 55 minutes before ending itself.  So I dug in to PowerShell and again it came up with a fantastic solution for looping until a certain time.

Here is a small bit of code that demonstrates a 2 minute loop before exiting.  you can use this as a basis for any script that you wish to run until a certain time.

#setup loop
$TimeStart = Get-Date
$TimeEnd = $timeStart.addminutes(2)
Write-Host "Start Time: $TimeStart"
write-host "End Time:   $TimeEnd"
Do { 
 $TimeNow = Get-Date
 if ($TimeNow -ge $TimeEnd) {
  Write-host "It's time to finish."
 } else {
  Write-Host "Not done yet, it's only $TimeNow"
 }
 Start-Sleep -Seconds 10
}
Until ($TimeNow -ge $TimeEnd)

The script waits for 10 seconds before looping, this is to stop it burning up processing resources for no good reason.

You can change the .addminutes line to be .addhours, .adddays, .addseconds etc. and it will work in the same way.

Posted on September 30, 2012 at 14:35 by admin · Permalink
In: Power Shell · Tagged with: ,

2 Responses

Subscribe to comments via RSS

  1. Written by Andreas Moe
    on 1 February 2013 at 8:34
    Reply · Permalink

    Excellent, just what I needed 😉

  2. Written by Zlatina
    on 17 June 2016 at 14:19
    Reply · Permalink

    Thank you, this is really useful!

Subscribe to comments via RSS

Leave a Reply