I have a script that is supposed to look at a logfile that starts filling with several hundred lines. While the log is filling, I need to look for two different conditions at the same time. If I find "Completed Successfully" then it will break the while loop and continue with the rest of the script. If it finds "Error" in the script, it will restart the server. Unfortunately this isn't working for me. It just sits until the timeout of the stopwatch. I'm not quite sure what is wrong here. Is there a better way to do this?
$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;
}