如何在 Powershell 中更轻松地操作时间跨度

How to easier manipulate timespan in powershell

我正在为 Powershell 做作业,其中一个功能是说明上次启动的时间。我正在打印日期和 'time since',日期工作正常,但我认为显示 'time since' 的代码太多了。我希望第一个值不为零。像这样:

1 Hour, 0 Minutes, 34 Seconds

而不是这样:

0 Days, 1 Hours, 0 Minutes, 34 Seconds

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

基于从一开始就删除最长 运行 的 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