Find all IP addresses from array

687 Views Asked by At

I have a lot of arrays which looks like

$a = 'Handshake', 'Success', 'Status', 200, '192.30.253.113', 'OK', 0xF

Information contained in this array may be different but there are IP addresses always in it (one or more, maximum three). I looking for a way for extract these addresses from array(s). What is the simplest way to do it? I ask your attention that position of IP addresses in arrays is various.

3

There are 3 best solutions below

1
On BEST ANSWER
$a.Where{!($_ -as [Double]) -and $_ -as [IPAddress]}

Or if you wanna be sure that IP addresses are valid use regular expression shown by @JulienNury

1
On

Regexp may be the fastest way:

$a -match '\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
0
On

Suppose you have multiple arrays such as $a, $b, $c etc. you can use a regular expression as such -

$arr = @()
$pattern = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

$a, $b, $c | Foreach {if ([Regex]::IsMatch($_, $pattern)) {
           $arr += [Regex]::Match($_, $pattern)
            }
        }
$arr | Foreach {$_.Value.Trim()}

Now you $arr will have all the IP addressess from all the multiple arrays.