Search code examples
powershelltextmatchlines

Powershell - how to obtain previous lines from text file?


I have a text file containing hundreds of lines of text containing database info.

I'm trying to extract the DatabaseIds for any database which is 35GB.

I would like to interrogate the file using Powershell and produce a text file containing all the matching databases.

So in essence, I would like to scan through the file, find a DatabaseSize which is 35 and then extract the corresponding DatabaseId from 3 lines previous.

I've looked all over the net but can't seem to find anything which can do this.

Example extract of text file:

ServerId = VMlinux-b71655e1
DatabaseId = db-ecb2e784
Status = completed
LocationId = 344067960796
DatabaseSize = 30

ServerId = VMlinux-0db8d45b
DatabaseId = db-cea2f7a6
Status = completed
LocationId = 344067960796
DatabaseSize = 35

ServerId = VMlinux-c5388693
DatabaseId = db-9a421bf2
Status = completed
LocationId = 344067960796
DatabaseSize = 8

etc

Solution

  • Try with something like this:

    (( GC myfile.txt | 
       Select-String 'DatabaseSize = 35' -Context 3 ).context.precontext)[0]
    

    In case of multiple match:

    (GC myfile.txt | 
    SELECT-STRING 'DATABASESIZE = 35' -Context 3 ) | % { ($_.context.precontext)[0] }