Author Posts

December 11, 2017 at 9:12 am

Good Morning kind nerds, I am struggling with something i'm sure is very easy to someone out there.

Essentially I want to search through a text log file for a string, if I find that string then I want to take the line BELOW the one I found and add it to a new array.

Then from that array I want to take the last 2 characters (which will be a number) in each element and total them up.

I have got this far (pathetic i know but in my defence I am not a coder for many many years)

$text= Get-Content -Path "C:\Users\me\test\log.txt"

$text| Where-Object {$_ -like '*String I want to find*'}

So I have done the first bit, finding the string I want – but that's as far as I managed to get.

December 11, 2017 at 11:09 am

I would do something like this

$Pattern =@("String I want to find", "somthing else maybe")
$test= get-content file.txt|Select-String -Pattern $pattern -SimpleMatch

December 11, 2017 at 11:23 am

Thank you John, that seems to achieve the first part as I have already done. Any ideas how I create the array of "next" lines?

December 11, 2017 at 12:06 pm

You could use the cmdlet Select-String and use the parameter -Context to capture the surrounding lines around a match.

December 11, 2017 at 1:03 pm

Thanks guys, I have now managed to get the line and the next line (which was the one that I wanted) into an array. Now to strip the lines I dont want 🙂

December 11, 2017 at 1:11 pm

this works sort of not sure what you want as a return if there is nothing found after that line or if the line after is null.
Also $test has everything in it and acts as an array. If you need to manipulate the data in each line further you would need some logic to split the lines. Hopefully the below gives you some help

$Pattern =@("String I want to find", "somthing else maybe")
$test= get-content file.txt|Select-String -Pattern $pattern -SimpleMatch -Context 0, 1 | % {$_.Context.PostContext}
$test |% { $testarray = $_ -split '#'
Write-Host $testarray[0]
Write-Host $testarray[1]

December 11, 2017 at 3:22 pm

Just wanted to thank all of you especially John, I have managed to get what I needed (with a little excel help afterwards)

December 11, 2017 at 11:39 pm

Glad I could help I just joined today and this was the first post I read.