1

I have a log file that appends a "restart successfully" line after each restart. Starting from the last "restart successfully" line, I want to find any lines after that contain a word from a list of search words.

How can I do this? I have partly working code below:

$contentsOfLog = Get-Content $inputFile
$keyWords =  $contentsOfLog | Select-String 'restart successfully'
$linenumbers = $keyWords.LineNumber
$linenumber = $linenumbers[$linenumbers.Length - 1]

$inputLines = ""

For ($i=$linenumber; $i -lt $contentsOfLog.length; $i++) {
    $line = $contentsOfLog[$i]
    $line = $line|select-string -pattern $error|Out-String
    $inputLines += $line.TrimEnd()
}

2 Answers 2

2

Obtain the line number to start from with a first pass through Select-String like you've already found, then use Select-Object -Skip to skip the lines prior:

$contentsOfLog = Get-Content $inputFile
$startFrom = $contentsOfLog |Select-String 'restart successfully' |Select -Last 1 -Expand LineNumber

$inputLines = $contentsOfLog |Select -Skip $startFrom |Select-String $error |Select -Expand Line
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Mathias as always :)
0

If you have a limit on the expected number of lines after your search string, then you can use Select-String's -Context switch:

$contentsOfLog = Get-Content $inputFile
($contentsOfLog | Select-String 'restart successfully' -Context 0,999).Context.PostContext | Select-String $error

This has the advantage that you're parsing in one pass, but the disadvantage that you need to have a limit on the number of lines searched. Note that setting the second number (999 in my example) to a ridiculously high value slows it down, and any value higher than System.Int32 can store will cause an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.