I was looking for PowerShell code to allow me to run a bunch of PowerShell code and then go to sleep until the top of the next hour and then run it again. Yes I could have created an hourly task in Task Scheduler, unless you do not have access to task scheduler because they treat it as an Administrator function and you only have user access.
Start-Sleep is a great function that allows you to specify the number of seconds to sleep before it starts the next PowerShell command. The code I kept finding in my searches would query Get-Date over and over until a specific time had occurred, which seemed like it was a little too intense. I just wanted something that no matter when my first chunk of code finished I could run it again or other stuff at the beginning of the next hour. If only Start-Sleep could take a time parameter instead of just seconds or milliseconds.
The answer is very simple and done with two lines of code. I am sure this could be combined into 1 line, but I am okay with 2 lines of code.
In this example I wanted to resume my program at the top of the hour. So something that finished at 1:27pm would resume at 2:00pm.
The first line of code figures out the current time and resets the minutes and seconds to zero. So 1:27pm becomes 1:00pm. Then adding an hour jumps you to the top of the next hour (2:00pm). TimeSpans calculate the total number of seconds from when you created the variable to the -End date/time. So the total seconds can then be fed into Start-Sleep and your program wakes up roughly at the beginning of the next hour and resumes.