首页 > 解决方案 > PowerShell New-TimeSpan 以天(s)小时(s)分钟(s)秒显示友好

问题描述

我一直在寻找类似于.NET 示例中的示例的 PowerShell 脚本。取一个 New-TimeSpan 并显示为 1 天 2 小时 3 分钟 4 秒。排除它的零,在需要的地方添加复数“s”。有谁有这个好用的吗?

据我所知:

$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"

标签: powershellformattingtimespan

解决方案


表格视图还不错:

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

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

推荐阅读