Powershell New-TimeSpan显示为天,小时,分钟,秒
问题描述:
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?
据我所知:
$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"
答
为什么不直接这样做呢?
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"
输出为:
Duration: 1 Day, 0 Hours, 15 Minutes, 3 Seconds
在持续时间的每个部分中有2个...
With 2 in each part of the duration ...
$StartDate = (Get-Date).AddDays(-2).AddHours(-2).AddMinutes(-2).AddSeconds(-2)
结果将是这样:
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.