我可以在while循环中的一个日志文件中有两个“尾巴”,其中一个条件做某件事,而另一个条件做别的事情吗?

问题描述 投票:0回答:1

我有一个脚本,该脚本应该查看一个开始填充几百行的日志文件。在填充日志时,我需要同时查找两个不同的条件。如果我发现“成功完成”,它将打破while循环,并继续执行脚本的其余部分。如果在脚本中找到“错误”,它将重新启动服务器。不幸的是,这不适用于我。它只是一直停留到秒表超时为止。我不太确定这里出了什么问题。有更好的方法吗?

$Comp="ServerA.domain"
$Logfile="\\$Comp\Logs\logfile1.txt"
$pattern1 = "Completed Successfully"
$Pattern2 = "Error"
$timeout = new-timespan -Minutes 5
$stopwatch = [diagnostics.stopwatch]::StartNew()
while ($stopwatch.elapsed -lt $timeout){
    try{
        $logContent2 = Get-Content -Path $Logfile -Tail 1000 | Select-String -Pattern $Pattern2 | Measure-Object | Select-Object -ExpandProperty Count
        $logContent1 = Get-Content -Path $Logfile -Tail 1000 | select-string -pattern $pattern1 | Measure-Object | Select-Object -ExpandProperty Count
        If ($logContent1 -gt 0) {
            Write-Host -Object "Compiled Successfully on $Comp" 
            #break;
        }
        ElseIf ($logContent2 -gt 0) {
            Write-Host -Object "Error Found on $Comp! Restart required. Rebooting..."
            Restart-Computer -ComputerName $Comp -Wait -For PowerShell -Force
        }
    }
    Catch{
        $Error[0] > \\$Comp\Logs\ErrorLog.txt
    }
}
If ($stopwatch.elapsed -ge $timeout){
    Write-Error -Message "$pattern1 did not appear" -ErrorAction Stop
    exit;
}
powershell while-loop tail multiple-conditions select-string
1个回答
0
投票

是的!我不小心在错误的地方放了休息。解决了。上面的代码有效,但是您需要中断循环(我在错误的位置中断了代码),并且在此示例中,我没有在代码中包含中断。

© www.soinside.com 2019 - 2024. All rights reserved.