我正在为Powershell分配任务,其中一项功能是说上次启动的时间。我正在打印日期和“自此的时间”,日期工作正常,但我认为显示“自从的时间”的代码太多。我希望第一个值不为零。像这样:
而不是这样:
$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)"
这段代码可以按我的意愿进行打印,但是对于这么少的东西来说似乎太多了。有没有更简单的方法?
最佳答案
确保检查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)"
关于shell - 如何在Powershell中更轻松地操纵时间跨度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49287595/