This post may contain affiliate links, please read our affiliate disclosure to learn more.
How to Get All IP Addresses From a File Using RegEx and PowerShell

How to Get All IP Addresses From a File Using RegEx and PowerShell

Author
 By Charles Joseph | Cybersecurity Researcher
Clock
 Published on December 26th, 2023
This post was updated on February 29th, 2024

I’m a Linux guy, so PowerShell isn’t exactly my forte, but when I found myself on a Windows 10 box without my familiar tools, I had to improvise.

I attempted to get a list of unique IP addresses from a text file. If I were on a *nix box, I’d issue the following command.

NordVPN 67% off + 3-month VPN coupon

Stay One Step Ahead of Cyber Threats

Want to Be the Smartest Guy in the Room? Get the Latest Cybersecurity News and Insights.
We respect your privacy and you can unsubscribe anytime.

$ grep -iEo “[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}” <filename> | sort | uniq -c

Unfortunately, Windows doesn’t natively have the grep command, so I did some digging.

I discovered that Windows maintains a program called findstr, which has a similar function albeit severely limited. You can’t narrow the output to matched text only.

So if you’re searching for IP addresses, and a line of text contains one with some additional surrounding text, findstr will return the entire line. This isn’t helpful.

So, I fired up PowerShell and issued the following command to get a similar output.

PS C:\Users\User\Desktop> $ips = Get-Content file.txt | Select-String -Pattern “[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}” -AllMatches | ForEach-Object {
$_.Matches | ForEach-Object {
$_.Value
}
} | Group-Object -NoElement

PS C:\Users\User\Desktop> $ips

Count Name
—– —-
7 1.2.3.4
5 2.3.4.5
1 3.4.5.6

Special thanks to Adam MacMurray for debugging a prior PS command that only pulled the first IP address from a line.

QUOTE:
"Amateurs hack systems, professionals hack people."
-- Bruce Schneier, a renown computer security professional
Scroll to Top