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: ,

9 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!

  3. Written by Ihtesham
    on 21 March 2017 at 16:13
    Reply · Permalink


  4. Written by Jayme
    on 3 December 2017 at 23:59
    Reply · Permalink

    i was wondering if i can use your scrip to run a command like this.

    “get-nccifssession | where-object Address – like 192.168.*”

    for 2 hours only and every 5 seconds. Where would i insert that get command from the above script? sorry really new to PS

  5. Written by Jayme
    on 4 December 2017 at 0:29
    Reply · Permalink

    i was testing it out and got it work… Thanks for the script!

  6. Written by Matt S.
    on 20 June 2018 at 14:18
    Reply · Permalink

    Great start, thanks for posting! I needed something that would run until a specific date (a network assessment). I edited $TimeEnd to read the specific date and time I needed rather than adding minutes.

    $TimeStart = get-date
    $TimeEnd = “Monday, July 9, 2018 9:00:00 AM”

  7. Written by Sumit.S
    on 15 January 2019 at 14:52
    Reply · Permalink

    Thank you. That’s was what i needed.

  8. Written by Ken
    on 31 January 2021 at 22:22
    Reply · Permalink

    Nice. I’ve learned a lot. Thank you.

  9. Written by Joseph
    on 3 May 2021 at 13:34
    Reply · Permalink


Subscribe to comments via RSS

Leave a Reply