Blog Post

Using New-TimeSpan to convert friendly time

,

twittergoogle_plusredditlinkedinmail

The question was this:

New-TimeSpan

This is just a quick/fast snippet in response to that question, but I can think of a ton of enhancements that could made. Hopefully it will be useful as a starting point for someone to customize for their own use.

function Convert-FriendlyTime
{
    param (
        [string]$FriendlyTime 
    )
    
    $Converted = $FriendlyTime.Split(" ")
    
    switch ($Converted[1])
    {
    "days"    { $parms = @{"days"=$Converted[0]}; break ;}
    "hours"   { $parms = @{"hours"=$Converted[0]}; break ;}
    "minutes" { $parms = @{"minutes"=$Converted[0]}; break ;}
    "seconds" { $parms = @{"seconds"=$Converted[0]}; break ;}
    "default" { $parms = $null; break ;}
    }
    if ($parms) {
        New-TimeSpan @parms
    } else {
        Throw "Invalid unit of time '$FriendlyTime'. Please use days, hours, minutes or seconds."
    }
}
Convert-FriendlyTime -FriendlyTime "2 days"
Convert-FriendlyTime -FriendlyTime "68 hours"
Convert-FriendlyTime -FriendlyTime "68 InvalidUnits"

PowerShell is fun!

twittergoogle_plusredditlinkedinmail

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating