“Wait-Until” Time with PowerShell – 60 Second Solutions

I had an example over the weekend whereby I needed to run a PowerShell command at a certain time due to a maintenance window.

Rather than using task scheduler, as this was a one-off, I decided to use PowerShell to achieve this.

Unfortunately, PowerShell does not natively have a ‘wait-until time’ cmdlet, so here’s the nearest equivalent:

(New-TimeSpan –End “DATE TIME IN FUTURE”).TotalSeconds | Sleep;

You can then put your own command to run at the specified time on the end.

Obviously you will need to leave the PowerShell window open, and it will appear to lock up until the time has elapsed, but it is a very quick and relatively easy way to delay commands.

Power-what now?

For those of you who are interested in how this works…

The ‘Sleep’ command takes a parameter of either seconds of milliseconds or seconds and will hold back execution of the PowerShell script until that time elapses.

‘Sleep’ also takes the seconds parameter from a pipe: ‘|’

‘New-Timespan’ creates a .net object called, funnily enough, a TimeSpan; this contains Hours,Minutes,Seconds etc between two given date times.

By default, the first datetime is “now” and –End specifies the 2nd datetime.

Taking the output from this, specifically the .TotalSeconds parameter and piping into sleep produces the desired effect. Neat!

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *