如何用PowerShell筛选Jenkins当日成功构建?
判断Jenkins当日是否存在成功构建
我需要确认Jenkins当日是否有成功构建。目前我通过以下代码遍历所有构建来获取成功构建信息,但必须遍历全部构建,无法直接筛选出当日构建:
$successInfo = $false foreach ($build in $buildsInfo) { $buildDate = Get-Date($build.timestamp) -Format "yyyy-MM-dd" if ($build.result -eq "SUCCESS" -and $buildDate -eq $currentDate) { $successInfo = $true break } }
为了筛选当日构建,我试过多种方法,以下是其中一种:
$startOfDay = (Get-Date).Date.ToShortDateString() $todaysBuilds = $commitStageInfo.builds | Where-Object { (Get-Date($_.timestamp) -match $startOfDay) }
注:我的Jenkins构建时间戳格式为timestamp=1711064553748(毫秒级Unix时间戳)。
优化解决方案
核心问题说明
Jenkins返回的timestamp是毫秒级Unix时间戳,直接用Get-Date($_.timestamp)会被当作秒级时间戳处理,导致日期转换错误,这是之前筛选失效的主要原因。下面是两种高效的优化方案:
方案1:通过时间戳范围精准筛选当日构建
先计算当日的毫秒级时间戳边界,直接过滤出当日构建后再检查是否有成功项,性能更优:
# 获取当日0点和次日0点的DateTime对象 $todayStart = (Get-Date).Date $todayEnd = $todayStart.AddDays(1) # 转换为毫秒级Unix时间戳(UTC时间计算) $todayStartTs = [Math]::Floor($todayStart.ToUniversalTime().Subtract((Get-Date "1970-01-01")).TotalMilliseconds) $todayEndTs = [Math]::Floor($todayEnd.ToUniversalTime().Subtract((Get-Date "1970-01-01")).TotalMilliseconds) # 筛选当日构建 $todaysBuilds = $buildsInfo | Where-Object { $_.timestamp -ge $todayStartTs -and $_.timestamp -lt $todayEndTs } # 检查是否存在成功构建 $successInfo = [bool]($todaysBuilds | Where-Object { $_.result -eq "SUCCESS" } | Select-Object -First 1)
方案2:修正日期字符串对比逻辑
如果偏好使用日期字符串对比,需先将毫秒时间戳转换为正确的DateTime对象:
$currentDate = (Get-Date).ToString("yyyy-MM-dd") $successInfo = [bool]($buildsInfo | Where-Object { # 将毫秒时间戳转为秒级,再转换为DateTime并格式化日期 $buildDate = (Get-Date -UnixTimeSeconds ($_.timestamp / 1000)).ToString("yyyy-MM-dd") $_.result -eq "SUCCESS" -and $buildDate -eq $currentDate } | Select-Object -First 1)
方案优势
两种方案都避免了无差别遍历全部构建(或提前过滤减少循环次数),同时修正了时间戳转换的错误,确保筛选逻辑准确。
内容的提问来源于stack exchange,提问作者Hemanth
相关产品推荐
相关产品推荐

