PowerShell New-TimeSpan Displayed Friendly with Day(s) Hour(s) Minute(s) Second(s)

北城以北 提交于 2020-12-15 04:56:12

问题


I've been looking for a PowerShell script similar to examples found in .NET examples. To take a New-TimeSpan and display is at 1 day, 2 hours, 3 minutes, 4 seconds. Exclude where its zero, add plural "s" where needed. Anybody have that handy?

This is as far as I got:

$StartDate = (Get-Date).ToString("M/dd/yyyy h:mm:ss tt")

Write-Host "Start Time: $StartDate"

# Do Something

$EndDate = (Get-Date).ToString("M/dd/yyyy h:mm:ss tt")

Write-Host "End Time: $EndDate" -ForegroundColor Cyan

$Duration = New-TimeSpan -Start $StartDate -End $EndDate
$d = $Duration.Days; $h = $Duration.Hours; $m = $Duration.Minutes; $s = $Duration.Seconds

Write-Host "Duration: $d Days, $h Hours, $m Minutes, $s Seconds"

回答1:


Why not doing it straight forward like this:

$StartDate = (Get-Date).AddDays(-1).AddMinutes(-15).AddSeconds(-3)
$EndDate = Get-Date

$Duration = New-TimeSpan -Start $StartDate -End $EndDate

$Day = switch ($Duration.Days) {
    0 { $null; break }
    1 { "{0} Day," -f $Duration.Days; break }
    Default {"{0} Days," -f $Duration.Days}
}

$Hour = switch ($Duration.Hours) {
    #0 { $null; break }
    1 { "{0} Hour," -f $Duration.Hours; break }
    Default { "{0} Hours," -f $Duration.Hours }
}

$Minute = switch ($Duration.Minutes) {
    #0 { $null; break }
    1 { "{0} Minute," -f $Duration.Minutes; break }
    Default { "{0} Minutes," -f $Duration.Minutes }
}

$Second = switch ($Duration.Seconds) {
    #0 { $null; break }
    1 { "{0} Second" -f $Duration.Seconds; break }
    Default { "{0} Seconds" -f $Duration.Seconds }
}

"Duration: $Day $Hour $Minute $Second"

Output would be :

Duration: 1 Day, 0 Hours, 15 Minutes, 3 Seconds

With 2 in each part of the duration ...

$StartDate = (Get-Date).AddDays(-2).AddHours(-2).AddMinutes(-2).AddSeconds(-2)

the result would be this:

Duration: 2 Days, 2 Hours, 2 Minutes, 2 Seconds

Of course you should wrap this in a function if you need it more than once. ;-)
And of course you can add more complex conditions if you like.




回答2:


The table view isn't bad:

new-timespan -Days 1 -Hours 1 -Minutes 1 -Seconds 1 | ft

Days Hours Minutes Seconds Milliseconds
---- ----- ------- ------- ------------
1    1     1       1       0


来源:https://stackoverflow.com/questions/61431951/powershell-new-timespan-displayed-friendly-with-days-hours-minutes-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!