PowerShell – Extract IP address from a text file

There are many ways you can perform this, writing a script for example, but I really like the one liner approach. Don’t you?

So here’s how I did:

(Select-String -Path .\SomeFile.txt -Pattern "\d{1,3}(\.\d{1,3}){3}" | %{$_.line.split("=")}) -match "\d{1,3}(\.\d{1,3}){3}"

Let me break this down for you.

I start by reading the content of the file looking for a specific pattern type. I’ve used Chris’s post for the exact pattern.

Select-String -Path .\SomeFile.txt -Pattern "\d{1,3}(\.\d{1,3}){3}"

In my case, the file contained a host name, followed by a ‘=’ and then the ip address. for example, a line from the file:


So I used the split function to split the string on a specific char. The command was passed with a pipeline:


The result in this case was something like this:



But I only needed the ip address. So ran a simple match to the whole string with the same pattern I’ve used in the Select-String. You will have to put the entire string before  -match in brackets. And the final result is simply the ip address:


Again, there are many ways you can get the exact result, maybe even in a better way. I would love to hear any suggestions on how to make my one-liner even better!


What do you think about this post?