2016-09-13 110 views
1

我的目标是编写一个脚本,用于检查事件持续时间的日志文件,根据日志条目计算持续时间(开始/结束),然后计算这些持续时间的平均值最近24小时,并确定它是否大于某个值(例如,让我们使用2小时)。到目前为止,我已经完成了前两个部分,正在适当检查日志并计算每个适用日志的持续时间。我只是不知道从最后一步开始,所有日志的持续时间平均。以下是我的代码到目前为止。ForEach循环,试图计算平均值

$imagesuccess = Get-ChildItem '\\server\osd_logs\success' -Directory | 
    Where-Object { 
     ($_.Name -like "P0*") -or (($_.Name -like "MININT*") -and 
     (Test-Path "$($_.FullName)\SCCM_C\Logs\SMSTSLog\Get-PSPName.log")) -and 
     ($_.LastWriteTime -gt (Get-Date).AddHours(-24)) 
    } 

$sccmlogpaths = "\\s0319p60\osd_logs\success\$($imagesuccess)\SCCM_C\Logs\SMSTSLog\smsts.log" 

foreach ($sccmlogpath in $sccmlogpaths) { 
    $imagestartline = Select-String -Pattern "<![LOG[New time:" -Path $sccmlogpath -SimpleMatch 
    $imagestarttime = $imagestartline.ToString().Substring(75, 8) 

    $imagefinishline = Select-String -Pattern "<![LOG[ Directory: M:\$($imagesuccess)" -Path $sccmlogpath -SimpleMatch 
    $imagefinishtime = $imagefinishline.ToString().Substring(71, 8) 

    $imageduration = New-TimeSpan $imagestarttime $imagefinishtime 
    $imagedurationstring = $imageduration.ToString() 
} 

回答

1

粗略你应该这样做:

$durations = foreach ($sccmlogpath in $sccmlogpaths) { 
    # [snip] 

    $imageduration = New-TimeSpan $imagestarttime $imagefinishtime 

    $imageduration # the 'output' of the foreach() {} 
} 


# $durations is now an array of timespans 

$measurements = $durations | Measure-Object -Average -Property TotalHours 
$averageHours = $measurements.Average 

if (2.5 -lt $averageHours) { 
    # code here 
} 

这确实总和(N)/数(n)的平均。

注意:如果您查询最近24小时,如果任何一个持续时间跨越午夜,New-TimeSpan将无法正常工作;它会将23:01 - > 00:01看作-23小时。

+0

@RyanBemrose是的!总的错误,感谢你接受它。 (我已经编辑来纠正它)。 – TessellatingHeckler

+0

令人敬畏的方法!我喜欢使用数组,我只是在从哪里开始画空白。我喜欢这种方法。有一个问题,我想我可能会遇到一些问题,其格式是我的工期。现在他们是HH:MM:SS,我想尽量保持这种状态。平均法可以很好地发挥作用吗? – LilithGoddess

+0

@LilithGoddess数组包含PowerShell'[TimeSpan]'对象,它们独立于您使用的字符串格式。 –