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: loop, PowerShell
In: Power Shell · Tagged with: loop, PowerShell
on 1 February 2013 at 8:34
· Permalink
Excellent, just what I needed 😉
on 17 June 2016 at 14:19
· Permalink
Thank you, this is really useful!
on 21 March 2017 at 16:13
· Permalink
Super…!!!
on 3 December 2017 at 23:59
· 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
on 4 December 2017 at 0:29
· Permalink
i was testing it out and got it work… Thanks for the script!
on 20 June 2018 at 14:18
· 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”
on 15 January 2019 at 14:52
· Permalink
Thank you. That’s was what i needed.
on 31 January 2021 at 22:22
· Permalink
Nice. I’ve learned a lot. Thank you.
on 3 May 2021 at 13:34
· Permalink
Awesome,Thanks
on 6 October 2021 at 7:31
· Permalink
Excellent, thank you.
on 10 November 2021 at 16:10
· Permalink
Really good. thanks