我正在为Powershell做一个任务,其中一个功能是说最后一次启动的时间。我打印日期和时间以来,日期工作正常,但我认为有太多的代码用于显示自'以来的时间。我希望第一个值不为零。像这样:
1小时,0分钟,34秒
而不是这样:
0天,1小时,0分钟,34秒
$bootDate = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$bootTime = $(Get-Date).Subtract($bootDate)
# Think there is an easier way, but couldn't find any :/
$time = ""
if($bootTime.Days -ne 0) {
$time = "$($bootTime.Days) Days, $($bootTime.Hours) Hours, $($bootTime.Minutes) Minutes, "
} elseif($bootTime.Hours -ne 0){
$time = "$($bootTime.Hours) Hours, $($bootTime.Minutes) Minutes, "
} elseif($bootTime.Minutes -ne 0){
$time = "$($bootTime.Minutes) Minutes, "
}
echo "Time since last boot: $time$($bootTime.Seconds) Seconds"
echo "Date and time: $($bootDate.DateTime)"
这段代码按我希望的那样打印出来,但对于这么少的东西来说似乎太多了。有更简单的方法吗?
答案 0 :(得分:2)
请务必检查TotalDays
而不是Days
。另外,我会将代码拆分为一个单独的函数:
function Get-TruncatedTimeSpan {
param([timespan]$TimeSpan)
$time = ""
if($TimeSpan.TotalDays -ge 1) {
$time += "$($TimeSpan.Days) Days, "
}
if($TimeSpan.TotalHours -ge 1){
$time += "$($TimeSpan.Hours) Hours, "
}
if($TimeSpan.TotalMinutes -ge 1){
$time += "$($TimeSpan.Minutes) Minutes, "
}
return "$time$($TimeSpan.Seconds) Seconds"
}
$bootDate = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$bootTime = $(Get-Date).Subtract($bootDate)
echo "Time since last boot: $(Get-TruncatedTimeSpan $bootTime)"
echo "Date and time: $($bootDate.DateTime)"
答案 1 :(得分:1)
一种简洁的解决方案,基于从一开始就使用0
运算符删除最长的-replace
值组件,该运算符使用正则表达式进行匹配(并且不通过有效指定替换字符串删除匹配项:
function get-FriendlyTimespan {
param([timespan] $TimeSpan)
"{0} Days, {1} Hours, {2} Minutes, {3} Seconds" -f
$TimeSpan.Days, $TimeSpan.Hours, $TimeSpan.Minutes, $TimeSpan.Seconds -replace
'^0 Days, (0 Hours, (0 Minutes, )?)?'
}
# Invoke with sample values (using string-based initialization shortcuts):
"0:0:1", "0:1:0", "1:0:0", "1", "0:2:33" | % { get-FriendlyTimespan $_ }
以上产量:
1 Seconds
1 Minutes, 0 Seconds
1 Hours, 0 Minutes, 0 Seconds
1 Days, 0 Hours, 0 Minutes, 0 Seconds
2 Minutes, 33 Seconds