Erick W
Erick W

Reputation: 25

How would I convert multiple strings to an IP address in Powershell so I can filter out IPv6

I have to pull a log file that contains a list of IP address within a windows log with some other stuff. I have figured out how to filter it down to just IP address, but I am struggling to convert it to an IP address object so I can filter out IPv6 entries.

In production I will use something like this to get the log:

$log = Get-Eventlog -Logname ABC -Source WIN-ABC -Newest 1 -ErrorAction stop

The .txt or log file looks like this:

Compare-DomainControllers

Customer.local
192.168.1.100
192.168.1.101
192.168.1.102 
2580:83:0:f2e:b25a:625f:c254:eb29
10.10.10.20 
etc...

What I have now in testing is:

$IPFullList = Get-content -path .\test.txt (Fake Log File) $IPOnly = $IPFullList | Select-String -match "[0-9]"

This returns a list of just the IPv4 and IPv6 items, but I am hoping to take that list and convert the entries into [IPAddress] objects so I can filter out the IPv6 items.

I have tried:

ConvertFrom-String -Inputobject $IPOnly

and:

Foreach ($IP in IPOnly){ [IPaddress] | Where-Object {$_.Type -ne "AAAA"} | Write-Host }

Non of them seem to do the trick. Any ideas or suggestions would be greatly appreciated!

Upvotes: 0

Views: 792

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You can do the following:

$IPFullList = Get-content -Path .\test.txt
$IPOnly = [IPAddress[]]($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim()

The result will be an array of IPv4 addresses stored in $IPOnly.

-match uses regex matching and will return matching strings if the input (left-hand side) is an array. If you are only passing a single string, -match will return $true or $false only.

Trim() method is used to remove white space from the beginning and end of each string.


If you want to process each IP individually, you can pipe into Foreach-Object:

$IPFullList = Get-content -Path .\test.txt
$IPOnly = ($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim() | Foreach-Object {
    [IPAddress]$_ # Returns the IPAddress object
}

Upvotes: 1

Related Questions