How to Calculate Time Differences for Scheduled Restarts in PowerShell?

0
31
Asked By CleverOtter92 On

I'm trying to calculate the time difference in seconds between the current time and a target time (like 8 PM, 10 PM, or 1 AM) in PowerShell. The issue I'm running into is that if the target time is before the current time, like 1 AM, it results in a negative time difference. I need it to always calculate the positive difference, even when the target time is after midnight. Any advice on how to properly handle this would be greatly appreciated!

5 Answers

Answered By NightOwlCoder On

Remember that `Restart-Computer` has its quirks. If you need to schedule it effectively, consider using scheduled tasks instead or `shutdown.exe` directly. This might help avoid all the back-and-forth with time spans. Also, you can use a complete datetime string for clarity, like `New-TimeSpan -End ([datetime]"06-02-2025 23:00")`. This way, you sidestep any locale issues.

CleverOtter92 -

I initially tried with `Restart-Computer`, but I switched to `shutdown.exe` once I realized it would be simpler. Good reminder about the datetime format!

Answered By WisePanda33 On

You should definitely use `New-TimeSpan` with actual datetime values. Instead of just specifying the target time like `New-TimeSpan -Start 10PM -End 1AM`, define the specific date too, like `New-TimeSpan -Start ('06/01/2025 5PM') -End ('06/02/2025 1AM')`. This way, it knows to calculate the time correctly between the two moments without going negative.

Answered By TechGuruDude On

A simple fix is to check if the target time is less than the current time and add a day if so. You can do this by comparing the two datetime objects. If the target is earlier or the same as the current time, then just add 24 hours to it before calculating the difference!

CleverOtter92 -

That's what I actually did, just added 86400 seconds when it's less than 0! Thanks for confirming that approach.

Answered By CodeNinja73 On

You could set up a function to handle this. Just grab the current time with `Get-Date`, compare it to your target time, and if it's less, add a day. Here's a quick example:

```powershell
function New-ForwardTimeSpan {
param ([DateTime]$TargetTime)
$CurrentTime = Get-Date
if ($TargetTime -le $CurrentTime) {
$TargetTime = $TargetTime.AddDays(1)
}
return New-TimeSpan -Start $CurrentTime -End $TargetTime
}
```
This should help you get the right number of seconds you're looking for! Let me know how it works out for you.

Answered By PixelMancer On

You could simplify this by creating a scheduled task that triggers your restart at the specified time. This way, you don’t have to deal with all the complexities of time calculations, and it can save you from needing a script running constantly.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.