In few of my scripts I am using timespan (TimeB – TimeA). Timespan is extremely powerfull in PowerShell, especially if you have ever done it in batches…
These scripts allows administrators to modify timespans. For example I have script that can automatically remove log files that are older than X days – and administrator can specify X value.
To keep it simple, you can use powershell translation, so you can specify timespans in format that is easy to understand:
“00:20:00” means 20 minutes.
To use it in powershell, simply use [timespan]”00:20:00”.
But what if you want to use period of time that is longer than 1 day? If you will try [timespan]”25:00:00”, you get following error:
Cannot convert value "25:00:00" to type "System.TimeSpan". Error: "The TimeSpan
could not be parsed because at least one of the hours, minutes, or seconds com
ponents is outside its valid range."
At line:1 char:11
+ [timespan]" <<<< 25:00:00"
Solution is pretty simple – timespan is using format days.hours.minutes.seconds, so you can change it to
1.00:00:00 (1 day) or 5.02:00:00 (5 days and 2 hours)":
PS C:\> [timespan]"5.02:00:00"
Days : 5
Hours : 2
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 4392000000000
TotalDays : 5.08333333333333
TotalHours : 122
TotalMinutes : 7320
TotalSeconds : 439200
TotalMilliseconds : 439200000