Kolob Canyon Kolob Canyon - 1 month ago 7
Bash Question

Powershell - Search for all IP addresses except 127.0.0.1 in all files and subdirectories

I want to search for all IP addresses except 127.0.0.1 in all files and subdirs of a given path.

I have tried:

function searchstr($string)
{
ls -Recurse | Select-String $string -List | Select Path
}


And this allows me to search for specific ip's

searchstr "192.153.133.2"


but not all ips...

I usually do this with regular expressions in eclipse like this: 1)
ctrl + h
=>
enter image description here

But this project is so big and has so many references to ips that eclipse dies when I try to run that regular expression on it.

I want my output to look like:

C:\full\path\to\file.php
C:\full\path\to\ipFile.txt


and to exclude entries with
127.0.0.1

Answer

Give this a try. It may be possible to modify the regex to perform the 127.0.0.1 exclusion in the Select-String command but I am not sure. I only know enough about regex to get by.

Get-ChildItem -Recurse `
| Select-String -Pattern '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' `
| ? { $_.Line -ne '127.0.0.1' } `
| Select-Object -ExpandProperty Path -Unique

Update

Give this a try.

Get-ChildItem -Recurse `
| Select-String -Pattern '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -AllMatches `
| ? { 
    $matches = ($_.Matches | Select-Object -Unique)
    return $matches.Count -gt 1 -or $matches[0].Value -ne '127.0.0.1' 
} `
| Select-Object -ExpandProperty Path -Unique

This should exclude files containing lines like the one the OP brings up in the comments:

ip address = 127.0.0.1

But it will not exclude files with lines such as the following (the suggested fixes would exclude files with this line):

ip address = 127.0.0.1; ip address = 8.8.8.8

Comments