gpt4 book ai didi

PowerShell New-TimeSpan 友好地显示为天(s)小时(s)分钟(s)秒(s)

转载 作者:行者123 更新时间:2023-12-05 03:53:53 27 4
gpt4 key购买 nike

我一直在寻找类似于 .NET examples 中的示例的 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"

最佳答案

为什么不直接这样做呢:

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

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

结果是这样的:

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

当然,如果你不止一次需要它,你应该把它包装在一个函数中。 ;-)
当然,您可以根据需要添加更复杂的条件。

关于PowerShell New-TimeSpan 友好地显示为天(s)小时(s)分钟(s)秒(s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431951/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com