Bill
Bill

Reputation: 554

how to get 2 values out of a string

Im hoping someone can help me with where to start, I want to pull some data out of some larger data My data looks like this:

IP-MIB::ipNetToMediaPhysAddress.13600001.10.4.48.1 = STRING: 36:b:7:0:41:31
IP-MIB::ipNetToMediaPhysAddress.13600001.10.4.49.21 = STRING: 3b:fa:a2:us:74:d9
IP-MIB::ipNetToMediaPhysAddress.13600001.10.3.50.22 = STRING: 3b:fa:a2:us:7b:f3

There is an IP Address on each line starting with 10. and the mac address which is on the end, thats what I want to get out. Ive been googling and am not sure where to start/what to do. Is Regex the way to go, or is there a better way, any examples would be appreciated. Thanks in advance

Upvotes: 1

Views: 38

Answers (1)

Lee_Dailey
Lee_Dailey

Reputation: 7489

here's one way to get that info ... [grin]

  • fake reading in a text file
    you will most likely want to use Get-Content or some pre-existing collection.
  • iterate thru the collection
  • use a named-capture-group regex to match on the IP & MAC
  • create a PSCustomObject from the match data
    you can get them from the $Matches automatic variable.
  • send the current object out to be collected by the $Results variable
  • display that collection

here's the code ...

# fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
IP-MIB::ipNetToMediaPhysAddress.13600001.10.4.48.1 = STRING: 36:b:7:0:41:31
IP-MIB::ipNetToMediaPhysAddress.13600001.10.4.49.21 = STRING: 3b:fa:a2:us:74:d9
IP-MIB::ipNetToMediaPhysAddress.13600001.10.3.50.22 = STRING: 3b:fa:a2:us:7b:f3
'@ -split [environment]::NewLine

$Results = foreach ($IS_Item in $InStuff)
    {
    $Null = $IS_Item -match '\.\d{8}\.(?<IPv4>.+) = .+: (?<MacAddress>.+)$'
    [PSCustomObject]@{
        IPv4 = $Matches.IPv4
        MacAddress = $Matches.MacAddress
        }
    }

$Results

you can use Export-CSV to send that to a nicely structured CSV file.

Upvotes: 2

Related Questions