Contact

Subscribe via Email

Subscribe via RSS

Categories

Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

PowerShell regexp match with lines above and below

Wasn’t aware of this until today when I needed to do this. The Select-String cmdlet in PowerShell can select strings based on a regexp (similar to findstr in regular command prompt) with the added benefit that it can also return context. Which is to say you can return the line that matches your pattern and also lines above or below it. Pretty cool!

In my case I needed to scan the output of portqry.exe and also get the UUIDs of the lines that match. These UUIDs are shown on the line above so I did something like this:

The -Context 1,0 switch is the key here. The first number tells the cmdlet how many lines before to show, the second number how many lines after.