The New-TimeSpan cmdlet provides a way to do date arithmetic within Windows PowerShell. For example, this command tells you the number of days between today’s date and New Year’s Eve 2016:
1 |
New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2016) |
When this command was run on Dic 2, 2016 we got back the following:
1 2 3 4 5 6 7 8 9 10 11 |
Days : 760 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 0 Ticks : 656640000000000 TotalDays : 760 TotalHours : 18240 TotalMinutes : 1094400 TotalSeconds : 65664000 TotalMilliseconds : 65664000000 |
Note. All those who knew that there were 65664000000 milliseconds between Dic 2, 2014 and December 31, 2016 please raise your hands.
To use New-TimeSpan you just need to pass it a pair of date-time values. The best way to do that is to use the Get-Date method; that helps ensure that you get a pair of date-time objects that New-TimeSpan can work with. For our first date, we simply use the Get-Date cmdlet without any additional parameters (note that the cmdlet must be enclosed in parentheses):
1 |
$(Get-Date) |
For our second date we also call Get-Date, but we tacked on the -month, -day, and -year parameters, along with the appropriate values:
1 |
New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2016) |
What if you need to know how long it is until a more specific time, such as 11:30 PM on December 31st? As usual, no problem: just include the -hour and the -minute parameters along with the appropriate values (for the hours, use the 24-hour time format). In other words:
1 |
New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2016 -hour 23 -minute 30) |