Home > Powershell, Scripting > Using regular expressions to parse files in PowerShell

Using regular expressions to parse files in PowerShell

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:

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"


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: