Parsing Raw Text (Part 2)

by Jan 2, 2017

In the previous tip we explained how you can use Select-String and a regular expression to extract valuable information from raw text results:

PS C:\> $data = ipconfig | select-string 'IPv4' 
PS C:\> [regex]::Matches($data,"\b(?:\d{1,3}\.){3}\d{1,3}\b") | Select-Object -ExpandProperty Value

PowerShell supports the -match parameter which also matches regular expressions. It can only find one match per line, though. In most scenarios, this is not a problem though because most often, there is only one match per line anyway. All you need to do is use -match inside a pipeline so the raw input is processed line by line:

PS C:\> ipconfig | 
  # do raw filtering to only get lines with this word
  Where-Object { $_ -like '*IPv4*' } |
  # do RegEx filtering to identify the value matching the pattern
  Where-Object { $_ -match '\b(?:\d{1,3}\.){3}\d{1,3}\b' } | 
  # return the results from -match which show in $matches
  Foreach-Object { $matches[0] }

Twitter This Tip! ReTweet this Tip!