Public/Format-PfaSecond.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Format-PfaSecond {
    <#
    .SYNOPSIS
    Formats seconds into a user friendly time.
     
    .DESCRIPTION
    Formats seconds into a user friendly time.
     
    .PARAMETER Seconds
    The number of seconds to convert.
 
    .PARAMETER AsInt
    Return value is an integer only.
 
    .EXAMPLE
    Format-PfaSecond -Seconds 14400
    4 hours
 
    .EXAMPLE
    Format-PfaSecond -Seconds 14400 -AsInt
    4
 
    .NOTES
    Author: brandon said
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [Int64]$Seconds,
        [Parameter(Mandatory = $false)]
        [Switch]$AsInt
    )

    $TimeSpan = New-TimeSpan -Seconds $Seconds

    switch ($TimeSpan) {
        {($TimeSpan.TotalDays % 1) -eq 0} {
            if (-not $AsInt) {
                "$($TimeSpan.TotalDays) days"
            } else {
                [Int64]$($TimeSpan.TotalDays)
            }
            break
        }
        {($TimeSpan.TotalHours % 1) -eq 0} {
            if (-not $AsInt) {
                "$($TimeSpan.TotalHours) hours"
            } else {
                [Int64]$($TimeSpan.TotalHours)
            }
            break
        }
        {($TimeSpan.TotalMinutes % 1) -eq 0} {
            if (-not $AsInt) {
                "$($TimeSpan.TotalMinutes) minutes"
            } else {
                [Int64]$($TimeSpan.TotalMinutes)
            }
            break
        } default {
            if (-not $AsInt) {
                "$($TimeSpan.TotalSeconds) seconds"
            } else {
                [Int64]$($TimeSpan.TotalSeconds)
            }
            break
        }
    }
}