ForEach循环不会产生所需的结果

时间:2016-10-31 17:04:41

标签: loops powershell logfile

我编写了一个脚本来识别日志文件中的时间戳:

    $start = Get-Content "C:\Webserverlogfiles\ise*.log" | select -first 1 -skip 6 


$end -match  '(([0-9][0-9]:){2}([0-9][0-9]))'
$end = $Matches[1]
$start -match  '(([0-9][0-9]:){2}([0-9][0-9]))' 
$start = $Matches[1]

$TimeDiff = New-TimeSpan $end $start


if ($TimeDiff.Seconds -lt 0) {
    $Hrs = ($TimeDiff.Hours) + 23
    $Mins = ($TimeDiff.Minutes) + 59
    $Secs = ($TimeDiff.Seconds) + 59 }
else {
    $Hrs = $TimeDiff.Hours
    $Mins = $TimeDiff.Minutes
    $Secs = $TimeDiff.Seconds }
$refreshrate = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs


echo $refreshrate

这将返回我之后的结果,即每次刷新之间的时间跨度。

现在我正在尝试扩展它,以便循环遍历整个文件。到目前为止,我的剧本只是挂起。

    $Workfrom = Get-Content "C:\Webserverlogfiles\ise*.log"

    Foreach ($Line in (Get-Content $Workfrom)) {

        $end = $line | Select-String 'ShowStatus = Reset Status' -SimpleMatch
        $end -match '(([0-9][0-9]:){2}([0-9][0-9]))'
        $end = $Matches[1]

        $start = $line | Select-String 'ShowStatus = Waiting for server ()' -SimpleMatch
        $start -match '(([0-9][0-9]:){2}([0-9][0-9]))'
        $start = $matches[1]

        $TimeDiff = New-TimeSpan $end $start       

        if ($TimeDiff.Seconds -lt 0) {
            $Hrs = ($TimeDiff.Hours) + 23
            $Mins = ($TimeDiff.Minutes) + 59
            $Secs = ($TimeDiff.Seconds) + 59 }
        else {
            $Hrs = $TimeDiff.Hours
            $Mins = $TimeDiff.Minutes
            $Secs = $TimeDiff.Seconds }

    $refreshrate = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs


    echo $refreshrate

    } 

除非我在ForEach循环中分组太多,否则我可以说这是正确的。我可以问我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

变化

$Workfrom = Get-Content "C:\Webserverlogfiles\ise*.log"

Foreach ($Line in (Get-Content $Workfrom)

$Workfrom = Get-Content "C:\Webserverlogfiles\ise*.log"

Foreach ($Line in $Workfrom) {

$workfrom已经是文本行。否则,也许你的第一行是Get-ChildItem