Old-Lost

ConvertTo-Approximation

Apr 19th, 2017
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ConvertTo-Approximation {
  2.     #.Synopsis
  3.     #  Calculates a relative text version of a duration
  4.     #.Description
  5.     #  Generates a string approximation of a timespan, like "x minutes" or "x days." Note this method does not add "about" to the front, nor "ago" to the end unless you pass them in.
  6.     #.Parameter Span
  7.     #  A TimeSpan to convert to a string
  8.     #.Parameter Before
  9.     #  A DateTime representing the start of a timespan.
  10.     #.Parameter After
  11.     #  A DateTime representing the end of a timespan.
  12.     #.Parameter Prefix
  13.     #  The prefix string, pass "about" to render: "about 4 minutes"
  14.     #.Parameter Postfix
  15.     #  The postfix string, like "ago" to render: "about 4 minutes ago"
  16.     [CmdletBinding(DefaultParameterSetName = "TwoDates")]
  17.     PARAM (
  18.         [Parameter(ParameterSetName = "TimeSpan", Mandatory, Position = 0)][TimeSpan]$TimeSpan,
  19.         [Parameter(ParameterSetName = "TwoDates", Mandatory, ValueFromPipeline)][Alias("DateCreated")][DateTime]$StartTime,
  20.         [Parameter(ParameterSetName = "TwoDates", Mandatory, Position = 0)][DateTime]$EndTime,
  21.         [Parameter(Position = 1)][String]$Prefix = "",
  22.         [Parameter(Position = 2)][String]$Postfix = "",
  23.         [Parameter(Position = 3)][ValidateCount(6, 6)][String[]]$Units = @('seconds', 'a minute', 'minutes', 'an hour', 'hours', 'days')
  24.     )
  25.     PROCESS {
  26.         if ($PSCmdlet.ParameterSetName -eq "TwoDates") {
  27.             $TimeSpan = $EndTime - $StartTime
  28.         }
  29.         "$Prefix $($TimeSpan.Approximate($Units)) $Postfix ".Trim()
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment