如何将PowerShell中连续时间限流计划数据汇总为指定格式?
实现限流比例数据的分段汇总
问题描述
通过以下PowerShell代码生成了周日各时间点的限流比例数据集:
$Times = @( "12:00 AM", "1:00 AM", "2:00 AM", "3:00 AM", "4:00 AM", "5:00 AM", "6:00 AM", "7:00 AM", "8:00 AM", "9:00 AM", "10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM", "2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM", "7:00 PM", "8:00 PM", "9:00 PM", "10:00 PM", "11:00 PM" ) $Example = @() $times | % {$time = $_; $Example += [pscustomobject]@{Day = 'Sunday'; Time = $time;RatelimitingSchedule = '100'}} $Example[5].RatelimitingSchedule = '50' 6..20 | % {$Example[$_].RatelimitingSchedule = '10'} $Example[21].RatelimitingSchedule = '50' $Example
该数据集每个时间点对应一条限流比例记录,需要整理为以下分段汇总格式:
- 5:00 AM至6:00 AM,限流比例50%
- 6:00 AM至9:00 PM,限流比例10%
- 9:00 PM至10:00 PM,限流比例50%
- 10:00 PM至次日5:00 AM,限流比例100%
解决方案
可以通过以下PowerShell代码实现连续相同限流比例的分段汇总:
# 为每条记录添加时间的分钟数值,方便顺序判断与排序 $timeWithValue = $Example | ForEach-Object { $totalMinutes = [datetime]::ParseExact($_.Time, "h:mm tt", $null).TimeOfDay.TotalMinutes $_ | Add-Member -MemberType NoteProperty -Name TimeMinutes -Value $totalMinutes -PassThru } # 初始化分组变量 $currentRate = $timeWithValue[0].RatelimitingSchedule $startTime = $timeWithValue[0].Time $summaryList = @() # 遍历数据,分组连续相同的限流比例 for ($i = 1; $i -lt $timeWithValue.Count; $i++) { if ($timeWithValue[$i].RatelimitingSchedule -ne $currentRate) { # 记录当前分段 $summaryList += [pscustomobject]@{ Start = $startTime End = $timeWithValue[$i-1].Time Rate = $currentRate } # 更新分组起始值 $currentRate = $timeWithValue[$i].RatelimitingSchedule $startTime = $timeWithValue[$i].Time } } # 添加最后一个分段 $summaryList += [pscustomobject]@{ Start = $startTime End = $timeWithValue[-1].Time Rate = $currentRate } # 处理跨天的100%分段:合并10:00 PM-11:00 PM和0:00 AM-4:00 AM的分段 $nightSegment = $summaryList | Where-Object { $_.Rate -eq '100' -and $_.Start -eq '10:00 PM' } $earlyMorningSegment = $summaryList | Where-Object { $_.Rate -eq '100' -and $_.End -eq '4:00 AM' } if ($nightSegment -and $earlyMorningSegment) { $mergedSegment = [pscustomobject]@{ Start = $nightSegment.Start End = "次日5:00 AM" Rate = $nightSegment.Rate } # 移除原分段,添加合并后的分段 $summaryList = $summaryList | Where-Object { $_ -ne $nightSegment -and $_ -ne $earlyMorningSegment } $summaryList += $mergedSegment } # 按时间顺序排序并输出要求的格式 $summaryList | Sort-Object { [datetime]::ParseExact($_.Start, "h:mm tt", $null).TimeOfDay.TotalMinutes } | ForEach-Object { "- $($_.Start)至$($_.End),限流比例$($_.Rate)%" }
代码逻辑说明
- 时间数值化:将时间字符串转换为当日总分钟数,确保后续排序和分段判断的准确性。
- 连续分组:遍历数据集,把连续使用相同限流比例的时间点归为一个分段,记录分段的起止时间。
- 跨天合并:针对跨天的100%限流分段,将夜间和凌晨的两个同比例分段合并为一个跨天描述。
- 格式输出:按时间顺序排序后,输出符合要求的列表格式。
内容的提问来源于stack exchange,提问作者arker
相关产品推荐
相关产品推荐

