Im new to powershell and Ive been trying to convert this string to a timespan object:
"2 Days 1 Hour 15 Minutes"
Ive tried several ways to input the format using parseexact but I cant seem to get the right format down.
Ive tried something like this :
[TimeSpan]::ParseExact('2 Days 1 Hour 15 Minutes', 'd \Days h \Hour MM \Minutes', $null)
CodePudding user response:
The TimeSpan parser is very sensitive, you need to escape everything that isn't a format string specifier:
[TimeSpan]::ParseExact('2 Days 1 Hour 15 Minutes', '%d\ \D\a\y\s\ %h\ \H\o\u\r\ %m\ \M\i\n\u\t\e\s', $null)
(I used the percent-sign notation for the specifiers (%d
instead of d
) to make them stand out in amongst all the \
's, but they're not required)
CodePudding user response:
The string version normally looks like this: '2.01:15:00'
, so [timespan]'2.01:15'
works.
CodePudding user response:
I am glad to see you have an answer. Another way would be to use named captures in a regex.
PS C:\> '2 Days 1 Hour 15 Minutes' -match '^(?<Days>\d )\D*(?<Hours>\d )\D*(?<Minutes>\d )\D*'
True
PS C:\> $matches
Name Value
---- -----
Hours 1
Minutes 15
Days 2
0 2 Days 1 Hour 15 Minutes
PS C:\> $Matches.Days
2
PS C:\> $Matches.Hours
1
PS C:\> $Matches.Minutes
15
PS C:\> $Ts = New-TimeSpan -days $Matches.Days -Hours $Matches.Hours -Minutes $Matches.Minutes
PS C:\> $Ts
Days : 2
Hours : 1
Minutes : 15
Seconds : 0
Milliseconds : 0
Ticks : 1773000000000
TotalDays : 2.05208333333333
TotalHours : 49.25
TotalMinutes : 2955
TotalSeconds : 177300
TotalMilliseconds : 177300000