Home > Powershell > Using regular expressions to parse files in PowerShell – Script of the Day

Using regular expressions to parse files in PowerShell – Script of the Day

How often do you find yourself needing to identify a string in a file somewhere.

For example, you have a log file, or a config file and you know it contains an IP address, but you do not want to manually trawl through this file (or even worse . . these files)

Regular expressions are pretty handy, as you can use them to identify (and edit) strings of text pretty simply. thik of it as a Replace function on steroids.

Here are some examples:
http://www.regular-expressions.info/quickstart.html

Anyway, back to our original question – we’d like to find an IP address in a file.

The first thing of course is to get hold of the text in our file – we’ll drop it into an array, so we can do a line by line comparison..

 
$var = @(Get-Content .\Access*.log)

Next, we need to create a Regex string pattern, which we will use as reference when we query out text – there are plenty examples available on the web (e.g. http://www.regular-expressions.info/examples.html) – but we just need one to find IP addresses:

 
$regex = [regex] "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

Lastly, we simply need to return a list of elements in our array, where the array matches the REGEX search string – again simple:

 
$regex.matches($var) | Select-Object -unique -property "Value"

so the full bit of code:

 
$var = @()
$var = Get-Content .\Access*.log
$regex = [regex] "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
$regex.matches($var) | `Select-Object -unique -property "Value"

Value
-----
206.13.132.82
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.