Thursday, November 20, 2014

Filtering large text files with PowerShell

I found myself struggling to opening and reading large text files and looking for errors. So I made this powershell script:

Get-Content file-name.txt | select -First 5000 |  Foreach-Object{ If ( $_ -match 'ERROR'){$_}  }

Simply it does three things:
Get-Content file-name.txt  gets all of the content of the text file
select -First 5000  gets me the first 5000 lines (this is optional if you want to search all the data)
Foreach-Object{ If ( $_ -match 'ERROR'){$_}  } gets lines with the word 'ERROR' in them

The result is the lines you want. You can use regex for better word matching as well.

To export the result. you can add a "> mytxt.txt" to the line and you will end up with a text file at your directory.