Skip to content

Instantly share code, notes, and snippets.

@adbertram
Created January 7, 2015 01:57
Show Gist options
  • Save adbertram/b0370601d180ca026163 to your computer and use it in GitHub Desktop.
Save adbertram/b0370601d180ca026163 to your computer and use it in GitHub Desktop.
function Convert-TimeStringToTimeSpan($TimeString) {
$AllowedLabels = (New-TimeSpan).Psobject.Properties.Name
## Add the singular values as well
$AllowedLabels += $AllowedLabels | foreach { $_.TrimEnd('s') }
## Strip the 'for' string
$TimeString = $TimeString.TrimStart('for ')
## Attempt to split on the 'and' string in case it was something like 1 hour and 15 minutes
$Values = $TimeString -split ' and '
$Hours = 0
foreach ($Value in $Values) {
$Split = $Value.Split(' ')
$Value = $Split[0]
if ($AllowedLabels -notcontains $Label) {
Write-Error "The label '$Label' is not a valid time label"
return $false
} elseif ($Value -notmatch '^\d+$') {
Write-Error "The time value '$Value' is not a valid time interval"
return $false
} else {
$Label = $Split[1]
## Make the label plural (if it's not already) to match New-TimeSpan's property name
if ($Label.Substring($Label.Length - 1, 1) -ne 's') {
$Label = $Label + 's'
}
Write-Verbose "Passing the label $Label and value $Value to New-TimeSpan"
## Convert the time to hours
$Params = @{ $Label = $Value }
$Hours += (New-TimeSpan @Params).TotalHours
}
}
[math]::Round($Hours,2)
}
@adbertram
Copy link
Author

Convert-TimeStringToTimeSpan -TimeString '1 day and 3600 seconds'
Convert-TimeStringToTimeSpan -TimeString '45 days and 5 hours'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment